New to Crystal, i don't understand why my code is not working

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

You’re basically running into Inheritance - Crystal.

Can fix it by doing [TestRecord.new] of JSON::Serializable.

2 Likes

Thanks a lot for your light-speed reply :slight_smile:
It’s Crystal-clear for me now :stuck_out_tongue:

Cheers!

1 Like