Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recover type in parametric composite type

Tags:

types

julia

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.

like image 711
tibL Avatar asked Dec 19 '22 08:12

tibL


2 Answers

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
like image 75
aviks Avatar answered Dec 31 '22 22:12

aviks


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.

like image 29
mdavezac Avatar answered Dec 31 '22 21:12

mdavezac