The Crystal Programming Language Forum

Strange error message 'undefined method for Nil'

I have a compilation error when I try to use a class variable referencing itself:

(from class A)
 @b = B.new(self)
 @b.toto()

I have reproduced the error here: https://play.crystal-lang.org/#/r/7lmf
This example works if b is not a class variable for instance. My question is why the compiler thinks @b can be null since I initialise it just before using it?

Because you pass self to something else, and that something else could do anything, including reading @b which is not yet initialized.

You can do @b.not_nil!.toto() to workaround that.

Thank you for the workaround!

Actually, could it be because it isn’t defined in initialize?

Oh, yeah, that’s definitely it. I didn’t check the play link.