In Julia (< 0.6), when creating a parametric composite type such as MyType{T}
, is there a clean way to recover T
from an instance of that type?
Take their example from the doc:
type Point{T}
x::T
y::T
end
I can create an object p = Point(5.0,5.0)
, T
here will be matched to Float64
so that the corresponding object is a Point{Float64}
. Is there a clean way to recover Float64
here?
I could do
typeof(p.x)
But it feels like that's not the right thing to do.
When you need the type parameter, you should define a parametric method. That is the only proper way to access the type parameter.
So for a Point
,
function doSomething{T}(p::Point{T})
// You have recovered T
println(T)
end
The type is saved in the class information:
typeof(Point(1, 2)).parameters # -> svec(Int64)
It's more general than writing a specific function for it, but I'm not sure it's considered official.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With