Inheriting from a Type Parameter

I’m curious why Julia doesn’t let you define a parametric type that inherits from a parameter, e.g.

struct SomeType{T} <: T end

When I try this, Julia gives the error invalid subtyping in definition of SomeType.

It seems like this feature could be useful to systematically define types that behave like a T, but have a different implementation. For example, StructArrays.jl has the Lazy Iteration feature where it can create a LazyRow{T} that sort of behaves like a T (by having getproperty behave the same for a T and a LazyRow{T}). However, since LazyRow{T} cannot inherit from T (or in the case that T is a concrete type, inherit from supertype(T)), you can’t use a LazyRow{T} as an argument for a function that expects a T (or a supertype(T)).

E.g. I would like have something like:

abstract type AbstractFoo end
struct Foo 
    # some representation of a Foo
end

# some function that is specialized for AbstractFoo
bar(foo::AbstractFoo) = 0

# create a StructArray of Foos to get a different representation of a Vector{Foo}
using StructArrays
foos = StructArray(Foo() for i in 1:100)

# lazy representation of a Foo
lazy_foo = LazyRow(foos,1)

# I would like to be able to do this, but it doesn't work
bar(lazy_foo)

But since LazyRow{Foo} cannot automatically inherit from AbstractFoo, this can’t be done.

Hi, welcome to the community! See here for a short discussion and the semi-official answer to that request:

2 Likes