How to get the parameter of a parameteric type wihtout looking at the fields

I want to retrieve the parameter of a parametric type of an object.
There are already several discussion on this, here or on SO, but I don’t want to look up at the object fields, as this would be application-specific, it is deep in my real case and it could change in the future.

So far this works:

julia> struct Foo{T}
           x::T
       end

julia> a = Foo(2.2)

Foo{Float64}(2.2)

julia> b = Foo(2)
Foo{Int64}(2)

julia> get_parametric_type(a::Foo{T}) where { T }= return T
get_parametric_type (generic function with 1 method)

julia> get_parametric_type(b)
Int64

But how do I generalise the function to all parametric types with a single parameter ? For example

julia> struct Goo{T}
           y::Int64
           z::T
       end

julia> c = Goo(1,1)
Goo{Int64}(1, 1)

julia> get_parameteric_type(c)
ERROR: UndefVarError: get_parameteric_type not defined
Stacktrace:
 [1] top-level scope
   @ REPL[8]:1

(and as we are here, not really need now, but could be useful, how to get all the parameters of an object foo::XXX{T1,T2,T3}(T1,T2,T3) ? )

EDIT: I see that the answer on the old thread on SO still works:

get_parameteric_types(obj) = typeof(obj).parameters

but it feels a bit a hacky, as it uses internals of Julia, still l don’t think that this is going to change soon :slight_smile:

1 Like