Reputation: 1371
I just tried out to define multiple methods for a function dependend only on a single input. The single input being different types and the behaviour should change according to the input type.
The problem is it's not working because only the last "version" of the function definition is being stored.
Here is the code:
abstract foo
type bar <: foo end
type car <: foo end
type dar <: foo end
f(bar) = "bar"
f(car) = "car"
f(dar) = "dar"
methods(f)
> # 1 method for generic function "f":
> f(dar)
Am I missing something or is it not possible to implement different methods for a function dependend on a single input?
Upvotes: 1
Views: 82
Reputation: 8566
f(bar) = "bar"
is equivalent to f(bar::Any) = "bar"
,
here the bar
in the function declaration syntax is an argument, not the type you previously defined. they are in deferent scope.
f(car) = "car"
f(dar) = "dar"
what happened here is f(x::Any)
was overridden twice.
the right way is to define a function whose argument should be a type, so the type of that argument should be a DataType
, precisely Type{bar}
in your specific case.
f(::Type{bar}) = "bar"
f(::Type{car}) = "car"
f(::Type{dar}) = "dar"
Upvotes: 4