I am picking up a stale package that reads a specific type of text file (IGC file if anyone out there flies gliders).
I have come across a number of function declarations like this:
function parse(::Type{IGCPressureAltitude}, s::String)
return IGCPressureAltitude(parse(Int, s))
end
and
function parse(::Type{IGCGpsAltitude}, s::String)
return IGCGpsAltitude(parse(Int, s))
end
parse
has a parse definition for every kind of data line in the file format.
I think the only thing that does is support multiple dispatch by passing a raw type into the parse
function. Am I missing anything?
2 Likes
No, I believe you are right. This way, one can write generic code that calls the parse
function for a type that is easy to change.
You can read more about this here - depending on the implementation, this can be part of the Holy Trait pattern.
Perfect, thank you very much.
DNF
July 23, 2023, 6:33pm
5
You are right about this, but looking at your question title, “Type annotation without a variable name in a function declaration”, there is something more. You can also have something like
function foo(::Float64, y::String)
...
etc. That will dispatch on the type of the first input, but does not capture it in a variable.
1 Like
nsajko
July 23, 2023, 8:09pm
6
You can also use type unions to prevent code duplication. Your two methods could be replaced with a single method:
function parse(::Type{T}, s::String) where {
T <: Union{IGCPressureAltitude, IGCGpsAltitude},
}
return T(parse(Int, s))
end
Alternative notation:
const MyUnion = Union{IGCPressureAltitude, IGCGpsAltitude}
parse(::Type{T}, s::String) where {T<:MyUnion} = T(parse(Int, s))