peoj
Typespec for a type implementing behaviour
Let’s say I have a behaviour MyBehaviour and a function that may return any module implementing that behaviour. Is it possible to write a type spec for that?
For example (pseudo-code):
defmodule MyBehaviour do
@callback say_hello() :: String.t()
end
defmodule MyBehaviourImplA do
@behaviour MyBehaviour
def say_hello(), do: "Hello from A"
end
defmodule MyBehaviourImplB do
@behaviour MyBehaviour
def say_hello(), do: "Hello from B"
end
defmodule ThisIsWhereTheQuestionComesIn do
@spec get_module_implementing_behaviour() :: ?????
def get_module_implementing_behaviour(), do: MyBehaviourImplA
end
I want to specify that ThisIsWhereTheQuestionComesIn.get_module_implementing_behaviour/0 could return either MyBehaviourImplA or MyBehaviourImplB (or indeed any module that implements that behaviour).
My use case is for a configurable adapter pattern; I want to write a function that returns whatever the currently configured adapter is.
Thanks as always!
Most Liked
oren1991
I was looking for a similar solution, in the end I did something similar:
defmodule MyBehaviour do
# Define a type for the behaviour
@type t :: module()
@callback say_hello() :: String.t()
end
defmodule MyBehaviourImplA do
@behaviour MyBehaviour
def say_hello(), do: "Hello from A"
end
defmodule MyBehaviourImplB do
@behaviour MyBehaviour
def say_hello(), do: "Hello from B"
end
defmodule ThisIsWhereTheQuestionComesIn do
# Using the type of the behaviour module
@spec get_module_implementing_behaviour() :: MyBehaviour.t
def get_module_implementing_behaviour(), do: MyBehaviourImplA
end
Does not do much with the typechecks but maybe more readable than simple module or hardcode the exact module into the @spec 
eksperimental
I think all you can do is:
@spec get_module_implementing_behaviour() :: module()







