Compiler error assigning `nil` to instance var

Hi, I am thinking of another question.

Following code not work

class A
  def initialize
    @x : Int32? = nil
  end
end

a = A.new

#  3 | @x : Int32? = nil
#      ^
# Error: instance variable @x of A was inferred to be Nil, but Nil alone provides no information

But following code is working.

class A
 @x : Int32?

 def initialize
   @x = nil
 end
end

So, this is also because not having the option to choose everything is simplified, right?

I think it’s because you’re typing the ivar within a method. If you remove the = nil you get the actual problem that:

Error: declaring the type of an instance variable must be done at the class level

The error you’re getting is because the ivar isn’t typed at the class level, its assumed to be nilable, but since you’re assigning nil the type it infers is Nil which probably isn’t what you want.

I think this is a bug. Please report it. Thank you!

1 Like

Sorry, how to report it? what is the expected behavior for the former code? 1 or 2 ?

  1. shouldn’t raise error?

  2. should raise error, but with a more non-confused message?

I think it should just work.