Struct with Multiple Dispatch

I think it a bit misleading if you speak of “Multiple dispatch of struct”. There is multiple function dispatch. I’m starting with a fresh REPL here. I you define your struct MyStruc, you implicitly define a function MyStruc with two methods:

julia> mutable struct MyStruc
           C::Float64
           a::Int64
       end

julia> methods(MyStruc)
# 2 methods for type constructor:
[1] MyStruc(C::Float64, a::Int64) in Main at REPL[1]:2
[2] MyStruc(C, a) in Main at REPL[1]:2

but it does not do what you want, since

julia> MyStruc(123, 4.56)
ERROR: InexactError: Int64(4.56)
Stacktrace: ...

Therefore you define another method like

julia> MyStruc(C::Int64, a::Float64) = MyStruc(C, Int(round(a)))
MyStruc

julia> methods(MyStruc)
# 3 methods for type constructor:
[1] MyStruc(C::Float64, a::Int64) in Main at REPL[1]:2
[2] MyStruc(C::Int64, a::Float64) in Main at REPL[3]:1
[3] MyStruc(C, a) in Main at REPL[1]:2

julia> MyStruc(123, 4.56)
MyStruc(123.0, 5)

In your case then you create a 2nd function, MyFunction with two methods, dispatching on Float64 and Int64:

julia> MyFunction(C::Float64; aValue) = MyStruc(C,aValue)
MyFunction (generic function with 2 methods)

julia> MyFunction(C::Int64; bValue) = MyStruc(C,bValue)
MyFunction (generic function with 2 methods)

julia> methods(MyFunction)
# 2 methods for generic function "MyFunction":
[1] MyFunction(C::Int64; bValue) in Main at REPL[7]:1
[2] MyFunction(C::Float64; aValue) in Main at REPL[6]:1

The problem with the 2nd parameter is not resolved by that since without the 3rd method for MyStruc above you get the same InexactError if you do MyFunction(123, bValue=4.56). Therefore MyFunction does not help.

BTW: MyFunction(C::Float64; aValue=a) assumes a being a global variable or a constant present in the current scope.

1 Like