The Crystal Programming Language Forum

Assigning class references to ivars

class Zone
  property level_info : Int32
  
  def initialize(map_id, player)
    player.in_zone_obj = self
    @level_info = map_id
  end
end

class Client
  property in_zone_obj : Zone?
end


player = Client.new

Zone.new(1, player)

Error: instance variable ‘@level_info’ of Zone was not initialized directly in all of the ‘initialize’ methods, rendering it nilable. Indirect initialization is not supported.

If @level_info is placed above player.in_zone_obj = self, there is no error.

However, even if @level_info is placed above, this still works:

if zone = player.in_zone_obj
	pp zone.level_info
end

Because it’s a reference.

So, what can I takeaway from this? If assigning a class reference to an ivar, it must be done at the very end of the initialize method, correct?

The issue here is that when you do player.in_zone_obj = self at that point @level_info is not set yet, which would leave it uninitialized within Client. I.e. which could go to use it before it’s actually initialized.