Reputation: 4906
Is there a way to check if a variable is of a custom type in Erlang?
Suppose I have some records and types defined in an .hrl
file:
-record(custom_record, {
attr1 :: list(),
attr2 :: binary(),
attr3 :: tuple()
}).
-record(another_record, {
attr1 :: list(),
attr2 :: binary(),
}).
-type custom_record() :: #custom_record{}.
-type another_record() :: #another_record{}.
-type custom_records() :: custom_record() | another_record().
Is there an easy way to check if a record is a custom_record
in my Erlang code? Something like this would be nice:
is_custom_type(CustomRecord, custom_records). %=> true
I looked through the docs and didn't see any build-in functions that did this.
Upvotes: 2
Views: 3699
Reputation: 5998
The Erlang standard library contains the is_record()
BIF, that checks if the first element of a tuple is the appropriate atom, see is_record/2 so you can test your variable like is_record(Var, custom_record)
.
Upvotes: 7
Reputation: 2593
There are no custom types in Erlang. Records are just syntactic sugar for tuples tagged with the atom and of the same length. Typespecs are used solely by dialyzer and nothing else.
Upvotes: 2
Reputation: 4571
You could use pattern matching for this purpose:
is_custom_type(#custom_record{} = _Record) -> true;
is_custom_type(_) -> false.
Upvotes: 1