Omitting type parameters on dispatch: accepted or implementation detail?

I am unsure if omitting additional type parameters on dispatch is an accepted and stable language behavior, or if it should be avoided, meaning doing things like this:

julia> using StaticArrays

julia> f(x::SVector{3}) = 3
f (generic function with 1 method)

julia> f(x::SVector{2}) = 2
f (generic function with 2 methods)

julia> x = rand(SVector{3,Float64});

julia> f(x)
3

julia> x = rand(SVector{2,Float64});

julia> f(x)
2

instead of being exhaustive and using:

julia> f(x::SVector{3,T}) where T = 3
f (generic function with 2 methods)

The first option of course works, but should we rely on that?

Yes.

From the manual: “Type parameters may be omitted when they do not need to be referenced or restricted.”

(The manual could be a lot more explicit about this, however — it might be good to add a subsection on omitting type parameters.)

3 Likes

It’s fine in dispatch (i.e. method arguments), but don’t (by accident) use those incompletely typed structs (or aliases for them) in type definitions, as noted in this discourse post. You’ll induce type instability in the calling code when accessing those fields.

2 Likes