With the new Julia 1.3 release candidates out, I’m trying to take advantage of defining a function on an abstract type. However struggling big time to figure out how to leverage it when also using modules.
The below example goes wrong because the expression “l::Person)(msg)= greeting(l, msg)” is defined within the module Dummy and cannot see the greeting implementation outside Dummy. So it gets a “greeting not defined” error (if I don’t use modules, everything works as expected).
Any ideas are welcome how to workaround this.
abstract type Person end
(p::Person)(msg)= greeting(p, msg)
struct RealPerson <: Person
greeting(p::RealPerson, msg) = println(msg, p.name)
person = RealPerson("Peter")
This isn’t really about the use of an abstract type; it’s just following the rules for all functions and methods in Julia (see https://docs.julialang.org/en/v1/manual/methods/ ).
You need to somehow indicate that the
greeting function you’re calling in Dummy is the same function you’re defining outside of it. The fact that they happen to have the same name is not enough.
In this case, you can declare the function inside
Dummy and implement a new method for it outside:
Dummy.greeting(p::RealPerson, msg) = ...
If you don’t want to write out
Dummy.greeting(, you can do:
import .Dummy: greeting
greeting(p::RealPerson, msg) = ...
Thanks, that clarifies it!!!
And indeed you’re right, this is not specific to functions on abstract types. I guess just first time I encountered it with one of my own modules while just coincidentally I was playing with abstract types.