Hello there!
I’m really enjoying Crystal these last days, I come from Ruby and it’s very pleasant to work with Crystal!
Unfortunately, I’m a bit stuck with the following code:
require "json"
class Output
include JSON::Serializable
alias DataStruct = Hash(String, Array(JSON::Serializable) | JSON::Serializable)
@data : DataStruct
def initialize
@data = DataStruct.new
end
def [](key)
@data[key]
end
def []=(key, value)
@data[key] = value
end
def to_json(json)
@data.to_json(json)
end
end
class TestRecord
include JSON::Serializable
@name : String
def initialize(@name = "Hello World")
end
end
pp Output{ "records" => [TestRecord.new] }
It raises the following error:
Error: instance variable '@value' of Hash::Entry(String, Array(JSON::Serializable) | JSON::Serializable) must be (Array(JSON::Serializable) | JSON::Serializable), not Array(TestRecord)
but the same code is working properly with:
pp Output{ "records" => TestRecord.new }
Playground link: Carcin
What is wrong with my code please? :(
Cheers