Modules and multiple dispatch

module

#1

Hello everyone! I have been struggling with understanding how modules work together with multiple dispatch. What I want is to subtype abstract type defined in the module to overload specific, previously known methods. The code which shows my struggle is:

module FooTest

abstract type Foo end
foomethod(foo::Foo) = error("$(typeof(foo)) needs to implement foomethod")
hellofoo(foo::Foo) = @show foomethod(foo)

export Foo, foomethod, hellofoo
end
import Test: Foo, foomethod, hellofoo

### Extending Foo

struct Bar <: Foo end
foomethod(bar::Bar) = "Bar hello"

### Now testing the thing 

bar = Bar()
hellofoo(bar)

WARNING: could not import Test.Foo into Main
WARNING: could not import Test.foomethod into Main
WARNING: could not import Test.hellofoo into Main
ERROR: LoadError: Bar needs to implement foomethod
Stacktrace:
 [1] error(::String) at ./error.jl:33
 [2] foomethod(::Bar) at /home/akels/BtSync/Projects/FooTest/src/FooTest.jl:4
 [3] macro expansion at ./show.jl:555 [inlined]
 [4] hellofoo(::Bar) at /home/akels/BtSync/Projects/FooTest/src/FooTest.jl:5
 [5] top-level scope at none:0
 [6] include at ./boot.jl:317 [inlined]
 [7] include_relative(::Module, ::String) at ./loading.jl:1044
 [8] include(::Module, ::String) at ./sysimg.jl:29
 [9] include(::String) at ./client.jl:392
 [10] top-level scope at none:0
in expression starting at /home/akels/BtSync/Projects/FooTest/test/runtests.jl:11

#2
julia> import Test: Foo, foomethod, hellofoo
WARNING: could not import Test.Foo into Main
WARNING: could not import Test.foomethod into Main
WARNING: could not import Test.hellofoo into Main

These warnings are important. Your module is called FooTest, not Test (which is a stdlib module).

Edit: by the way, as a matter of style I think it’s better to use FooTest.foomethod(bar::Bar) = "Bar hello" rather than importing the method. Much clearer what’s going on this way.


#3

:blush: That indeed was a problem in this example.