How do you check for the type of variable in Elixir

Starting in elixir 1.2 there is an i command in iex that will list the type and more of any Elixir variable.

iex> foo = "a string" 
iex> i foo 
Term
 "a string"
Data type
 BitString
Byte size
 8
Description
 This is a string: a UTF-8 encoded binary. It's printed surrounded by
 "double quotes" because all UTF-8 encoded codepoints in it are        printable.
Raw representation
  <<97, 32, 115, 116, 114, 105, 110, 103>>
Reference modules
  String, :binary

If you look in the code for the i command you'll see that this is implemented via a Protocol.

https://github.com/elixir-lang/elixir/blob/master/lib/iex/lib/iex/info.ex

If you want to implement a function for any Data type in Elixir, the way to do that is to define a Protocol and implementation of the Protocol for all the data types you want the function to work on. Unfortunately, you can't use a Protocol function in guards. However, a simple "type" protocol would be very straightforward to implement.


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