Skip to content

Instantly share code, notes, and snippets.

@ruxxzebre
Last active September 10, 2022 20:30
Show Gist options
  • Save ruxxzebre/4f5c1cec0cce473ba691d079452f37d8 to your computer and use it in GitHub Desktop.
Save ruxxzebre/4f5c1cec0cce473ba691d079452f37d8 to your computer and use it in GitHub Desktop.
Demo of issue with defprotocol
defprotocol Animal do
@fallback_to_any true
def warn(arg, arg2)
def greet(arg)
def speak(arg)
# Here I'm getting
# == Compilation error in file lib/animal.ex ==
# ** (CompileError) lib/animal.ex:6: undefined function defdelegate/2 (there is no such import)
# Then go to line 48
#
defdelegate kind(arg), to: Animal.Any
defdelegate describe(arg), to: Animal.Any
end
defimpl Animal, for: Any do
def greet(_), do: ""
def warn(_, _), do: ""
def speak(_), do: ""
def kind(animal) do
animal.__struct__
|> Module.split()
|> List.last()
|> String.downcase()
end
def describe(animal) do
"Animal #{Animal.kind(animal)} named by #{animal.name}!"
end
end
defimpl Animal, for: Dog do
def warn(dog, arg) do
IO.puts("Warning, #{dog.name}! It is #{arg}!!!")
end
def greet(_) do
IO.puts("Greetings!")
end
def speak(_) do
IO.puts("Imma speaking!!!")
end
end
defmodule Dog do
# Here I'm not getting any errors
# Would be grateful for help, it's kinda tricky to grasp the
# concept when Elixir won't let me do that.
# Maybe something was changed in some major patch, not sure.
defdelegate(kind(arg), to: Animal.Any)
defdelegate(describe(arg), to: Animal.Any)
@enforce_keys [:name]
alias __MODULE__
defstruct name: ""
def new(name), do: %Dog{name: name}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment