Search code examples
elixirtypechecking

How to check type of struct's field in Elixir?


Let's say I have:

defmodule Operator do

    defstruct operator: nil 

    @type t :: %Operator {
        operator: oper
    }

    @type oper :: logic | arithmetic | nil
    @type logic :: :or | :and
    @type arithmetic :: :add | :mul 

end

then I can:

o = %Operator{operator: :and}

Is it to possible to check whether o.operator is logic, arithmetic or nil ?


Solution

  • Typespecs in Elixir are annotations, you can't really interact with them from your code without repeating part of them. Therefore, you can write:

    def operator(%Operator{operator: op}) when op in [:or, :and, :add, :mul, nil] do
      ...
    end
    

    Or alternatively:

    @ops [:or, :and, :add, :mul, nil]
    
    def operator(%Operator{operator: op}) when op in @ops do
      ...
    end