Do you need to specify a type for class variables?

Class and instance variables always need to be typed.

Often, type inference can determine the type without explicit declaration.
But type inference can only work if you directly assign a value (class_getter bar = 17).
class_getter bar does not assign a value, so the compiler has nothing to go by to infer the type.
Even with a value, it sometimes doesn’t work when the resulting type is not directly obvious.

The compiler will ask you to type the variable if it cannot figure it out.
So you can just go by whether the compiler accepts it or not.

As a practical advise, it’s often helpful to add type annotations, even when they’re not required. It helps documenting the code.

This statement is not necessarily wrong, but it’s incomplete and apparently leads to misunderstanding. Type inference can only work if there’s a value from which to infer the type alongside the declaration.

1 Like