The Crystal Programming Language Forum

Create an array that can contain its own type?

In building a computer language, I have need for an array that can contain its own type (and other types). I tried this, it doesn’t work (and I just filed a bug on a variant that breaks the compiler).

alias ArrayValue = Array(Int32 | ArrayValue)
class MyArray < Array(ArrayValue)
end
x = MyArray.new
x << 1 # Won't compile.
x << x # Will compile, and the compiler claims this is the only overload for <<.
1 Like

It works. The Array can only contain ArrayValue and that’s always an Array. You can do it like this:

alias ArrayValue = Int32 | Array(ArrayValue)

class MyArray < Array(ArrayValue)
end

x = MyArray.new
x << 1
x << x
p x
2 Likes

OK, I see what I was doing wrong. Thanks!

1 Like