Organisation into submodules and multiple dispatch

Currently both submodules define separate functions that happen to share the name foo. Multiple dispatch isn’t working because those two foo() functions have nothing to do with one another, so there’s nothing for dispatch to do.

Fortunately, this is easy to fix. You need to define the function itself in the supermodule (you don’t need to give it any behavior, just declare that it exists), and then you need to explicitly extend that function in each submodule:

julia> module SuperModule
         # Define `foo()` but don't give it any methods yet
         function foo end
         
         # You can put this into SubModule.jl and do 
         # include("SubModule.jl") here, but I'm including 
         # it inline for this simple example.
         module SubModule1
           
          # Explicitly indicate that this is the *same* foo as in SuperModule
          import ..foo
           
          foo(x::Int) = println("hello Int")
        end
        
        module SubModule2
          import ..foo
          
          foo(x::Float64) = println("hello Float64")
        end
       end
Main.SuperModule

julia> SuperModule.foo(1)
hello Int

julia> SuperModule.foo(1.0)
hello Float64
12 Likes