Initialization

Hi there. I don’t understand why this code is ok for the complier:

class Person
 def initialize (@name : String)
  @age = 0
 end
end

and this gives an error:

class Person
 def initialize (@name : String)
  @age : Int32 = 0
 end
end

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

ok the message is clear but… why?

thx.

This is a matter of compiler stages.
Semantic analysis of type declarations at the class level happens early in the compilation process. This includes ivar declarations derived from method signatures (@name : String).
After that the compiler starts analyzing the main program. The body of a method is only visited when there’s a call to this method. At this point, the compiler already needs to know the shape of the type, i.e. which instance variables are defined.

I suppose it might technically be possible to extract ivar type declarations from method bodies in an earlier stage, similar to how it works with type declarations at the class level. In your example, the compiler could potentially derive the necessary information from the method body ahead of time. But there would be a number of caveats to that. And it makes the compiler more complex, with little benefit.

You need to declare instance variables at class level or via the convenience syntax for method parameters.

3 Likes

Quite complex… anyway it’s a bit strange that the compiler complains when I give it more information.
thank you

Hm, yeah I guess it’s a bit strange that assignment works, while type declaration does not. This may need some more research.