3 ms·
Personally, even when I do want something resembling type checking, I've found pattern matching / destructuring to be more than sufficient. With Elixir's struc
by yellowapple 10y ago
Personally, even when I do want something resembling type checking, I've found pattern matching / destructuring to be more than sufficient. With Elixir's structs, this is trivial:
def some_function(SomeStruct{} = some_struct) do
some_struct.foo + some_struct.bar
end
Or better yet, if I only want certain fields:
def some_function(SomeStruct{foo: foo, bar: bar}) do
foo + bar
end
This way, if the "type check" fails (that is, someone tries to use "some_function/1" on something that isn't a SomeStruct), there'll be a clear error to that effect.
Between this and protocols, I very rarely feel the need to reach for something like Dialyzer. YMMV, of course.
- boardwaalk 10y agoPattern matching is fantastic. Also, there are guards: def handle_info(msg, state) when is_tuple(msg) do # ... end I haven't written anything big with Elixir/Erlang yet, but I definitely feel more confident my Elixir code will work than Python, say. Not as much as Go, though. As an aside, comparing: {:ok, port} = Port.open(...) to something similar in Go: port, err := port.open(...) if err != nil { panic(err) } That's very convenient. Also, you can bind multiple times to a single argument (sort of like what you showed): def handle_info([], state = {ppid, _port}) do Supervisor.stop(ppid) {:noreply, state} end That's not a default argument, that's binding the second argument to state and the pid inside the state tuple.