Frage

In statically typed languages with generics, like C#, I can specify in the method signature that each of the map's keys is an atom and each value is a list of {string, int} tuple. How do I define the type specification for function arguments like that in Elixir?

PS: if you are reading this and have >1500 rating, could you please create a type-specification tag.

War es hilfreich?

Lösung

You would define it like so:

@type bar :: %{atom => [{binary, integer}]}

@spec foo(bar) :: bar
def foo(bar), do: bar

The above defines a new type, which is your map of atom keys to lists of binary/integer tuples, and then uses that type in the type spec for foo.

Andere Tipps

For inline spec it goes like this:

defmodule LousyCalculator do
  @spec add(number, number) :: {number, String.t}
  def add(x, y), do: {x + y, "You need a calculator to do that?!"}

  @spec multiply(number, number) :: {number, String.t}
  def multiply(x, y), do: {x * y, "Jeez, come on!"}
end

If you expect a structure then the type is:

@spec struct_returner_and_getter(%Struct_name1{}) :: %Struct_name2{}

Source: http://elixir-lang.org/getting-started/typespecs-and-behaviours.html

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top