Parametric type with value of custom type as type parameter

Hi everyone,

as the title suggests, I want to create a parametric type with the value of a custom type as type parameter. So for example

struct MyType
x::Int
end

struct MyParametricType{T}
x
MyParametricType(a) = new{a}(a)
end

This constructor works for “simple” inputs like MyParametricType(5) returns MyParametricType{5}(5). However this does not work for any instance of MyType (even though it is a bitstype) or a String. I also noticed that it does work for a singleton type defined like struct MySingletonType end.

I guess it has something to do with whether Val is defined for my input to MyParametricType.

So is it possible to attain this? And when does it work and when doesn’t it?

I am grateful for any input.

From the manual:

Both abstract and concrete types can be parameterized by other types. They can also be parameterized by symbols, by values of any type for which [isbits](https://docs.julialang.org/en/v1/base/base/#Base.isbits) returns true (essentially, things like numbers and bools that are stored like C types or structs with no pointers to other objects), and also by tuples thereof.

It works:

julia> isbits(MyType(3))
true

julia> MyParametricType(MyType(3))
MyParametricType{MyType(3)}(MyType(3))

First thank you for your answer and sorry for asking a question which is answered by the manual and for posting a wrong MWE.

It seems that the example I actually look at was (I don’t know why I changed this for my MWE)

struct MySymbolType
       x::Symbol
end

And then it doesn’t work. I assume because Symbol is not a bits type. However, I am still confused as to why

julia> MyParametricType(:a)
MyParametricType{:a}(:a)

julia> isbits(:a)
false

Works. I guess there is some special treatment for Symbols, but then I had hoped that MyParametricType(MySymbolType(:a)) also works.
But apparently that is not the case.

Thanks again for the answer

1 Like

Symbols are also special cased here, yes, as mentioned in the quoted section above:

They can also be parameterized by symbols, by values of any type for which isbits returns true (essentially, things like numbers and bools that are stored like C types or structs with no pointers to other objects), and also by tuples thereof.

(emphasis mine)

2 Likes

Yeah I see, thank you