Difference between Type.parameters and Type.types

I am trying to retrieve the parameters of a parametric type, and find that both parameters and types fields of Type provide what I want:

julia> VERSION
v"1.9.0-beta4"

julia> struct MyType{S,T}
           a::S
           b::T
       end

julia> m = MyType(1, 1.0)
MyType{Int64, Float64}(1, 1.0)

julia> typeof(m).parameters
svec(Int64, Float64)

julia> typeof(m).types
svec(Int64, Float64)

Is there any difference between the two?

This might give you an idea:

julia> struct MyType2{S}
           a::S
           b::Float64
       end

julia> m = MyType2(1, 1.0)
MyType2{Int64}(1, 1.0)

julia> typeof(m).parameters
svec(Int64)

julia> typeof(m).types
svec(Int64, Float64)
2 Likes

You can try the same with

struct MyType{S,T}
           a::S
           b::Vector{T} 
       end
3 Likes

However I would say it is usually bad practice to access language internals that way. If you need these types somewhere, the better way would be to get them via dispatch:

function f(m::MyType{S,T}) where {S,T}
    # do something with S or T
end
4 Likes

The “typical” way to extract these values is with functions like the following:

typeS(::Type{<:MyType{S,T}}) where {S,T} = S
typeT(::Type{<:MyType{S,T}}) where {S,T} = T

Internals like <type>.parameters are allowed to change in the future, so be warned that implementations using them may require revision in a later version.

You can also look into the fieldtype function.

3 Likes