elixir

How do you check for the type of variable in Elixir


In Elixir how do you check for type such as in Python:

>>> a = "test"
>>> type(a)
<type 'str'>
>>> b =10
>>> type(b)
<type 'int'>

I read in Elixir there are type checkers such as 'is_bitstring', 'is_float', 'is_list', 'is_map' etc, but what if you have no idea what the type could be ?


Solution

  • There's no direct way to get the type of a variable in Elixir/Erlang.

    You usually want to know the type of a variable in order to act accordingly; you can use the is_* functions in order to act based on the type of a variable.

    Learn You Some Erlang has a nice chapter about typing in Erlang (and thus in Elixir).

    The most idiomatic way to use the is_* family of functions would probably be to use them in pattern matches:

    def my_fun(arg) when is_map(arg), do: ...
    def my_fun(arg) when is_list(arg), do: ...
    def my_fun(arg) when is_integer(arg), do: ...
    # ...and so on