Overload zero for a parametric type

Hello, I would like to add a zero function for a custom parametric type.

This code for example

struct Point{T}
Point{T}() where T = Point(zero(T))
Point() = Point(0)

can produce “zero” elements with


But when I try to define

Base.zero(::Point{T}) where T = Point{T}(zero(T))

and call it with zero(Point{Int64})

I get the following error:

ERROR: LoadError: MethodError: no method matching zero(::Type{Point{Int64}})
Closest candidates are:
  zero(::Type{Base.LibGit2.GitHash}) at libgit2/oid.jl:106
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuildItem}) at pkg/resolve/versionweight.jl:82
  zero(::Type{Base.Pkg.Resolve.VersionWeights.VWPreBuild}) at pkg/resolve/versionweight.jl:124

Why can’t julia dispatch to the right method is this case?

Look at the error message:

Just define a method

Base.zero(::Type{Point{T}}) where T = Point{T}(zero(T))

for the type.

1 Like

You need ::Type{Point{T}}

1 Like

Thanks, I see, I thought, just :: in front is enough to tell that it is a type.

No it is unrelated f(::SomeThing) is just a short hand f(unused_argument::SomeThing). So f(::Point) is short for f(unused_point_instance::Point), while f(::Type{Point}) is short for f(WeAlreadyKnowThisIsPoint::Type{Point})