crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.42k stars 1.62k forks source link

The error message that instance variable declaration must be in class scope should take precedence #12708

Open zw963 opened 1 year ago

zw963 commented 1 year ago

Original link: https://forum.crystal-lang.org/t/confusing-error-output-instance-variable-x-of-a-was-inferred-to-be-nil/5053

Following is code:

class A
  def initialize(x)
    @x : Int32? = x
  end
end

a = A.new(100)
In 1.cr:3:5

 3 | @x : Int32? = x
     ^-
Error: declaring the type of an instance variable must be done at the class level

Okay, the output is expected, because i declare the type of @x wrong way.

Then, i change to this:

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

a = A.new(100)
In 1.cr:3:5

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

The key point of this issue is, the above two error message, which one is more important?

If we should show the first class scope error msg at first?

thanks

asterite commented 1 year ago

Just a note that it seems the compiler's message was telling you to put the declaration at the class level, like this:

class A
  @x : Int32? # This is what the compiler was telling you

  def initialize(x)
    @x = x
  end
end
zw963 commented 1 year ago

Just a note that it seems the compiler's message was telling you to put the declaration at the class level, like this:

Yes, those message intention clear enough, the key point is, after i add || nil, new error message override the class level one, i updated my issue content for clarify.