Behaviour and Typespec

Hi, all,

Mb it’s silly question :pensive:, but: is there any possibility to define a behaviour in a function’s spec?

for example we have:

defmodule SomeBehaviour do
  @callback do_it() :: any()
end

defmodule Adopter1 do
  @behaviour SomeBehaviour

  def do_it(), do: :done
end

defmodule Adopter2 do
  @behaviour SomeBehaviour

  def do_it(), do: :not_done
end

defmodule SomeModule do
  # So, what's the right @spec for this function, if I'd like to specify SomeBehaviour adopters usage?
  # The first thought is to use just SomeBehaviour.t with @type t :: __MODULE__ in SomeBehaviour definition,
  # but as for me it seems too strict and any adopter will not pass the check
  def do_it_with(adopter), do: adopter.do_it()
end

Thanks.

6 Likes

Probably the best you can do is to spec it as module - the type system is not powerful enough to express something more advanced.

The idea to add @type t :: module in the behaviour is probably a good one. While it’s still the same when checked with dialyzer, it expresses much more when treating type specs as documentation.

6 Likes

Unfortunately @type t :: module + @spec(SomeBehaviour.t) will check just for any module, not a behaviour adopter. :frowning: well, let it be

2 Likes