FNj
FNj

Reputation: 33

Parametric type not working as expected in Julia

I am pretty new to Julia and this is driving me nuts:

type MyType{T<:Number}
  x::T
  y::T
end
Float64 <: Number # this is true
MyType{Float64} <: MyType{Number} #this is for some reason false

I would of course expect that, if I created two concrete types derived from the same parametric type one by using an abstract type as the parameter and the other by using concrete type that is a subtype of the abstract type used for the first derivation, the type derived using the concrete type would be a subtype of the one derived using the abstract type.

That sentence took me a while to compose. Hopefully it is intelligible.

Upvotes: 1

Views: 128

Answers (1)

spencerlyon2
spencerlyon2

Reputation: 9676

This is the expected behavior: Types in Julia are invariant rather than covariant or contravariant. Quoting from the docs:

Julia's type parameters are invariant, rather than being covariant (or even contravariant). This is for practical reasons: while any instance of Point{Float64} may conceptually be like an instance of Point{Real} as well, the two types have different representations in memory:

An instance of Point{Float64} can be represented compactly and efficiently as an immediate pair of 64-bit values; An instance of Point{Real} must be able to hold any pair of instances of Real. Since objects that are instances of Real can be of arbitrary size and structure, in practice an instance of Point{Real} must be represented as a pair of pointers to individually allocated Real objects.

See the manual

Upvotes: 7

Related Questions