With the new mandatory type annotations, it is inevitable that one will want to both specify the type of an (instance/global) variable and initialize it. It's also useful in the case where the variable's type should be broader than the initial value's type.
Currently, it would have to be written like this:
$texture : Texture
$texture = get_texture()
@data : String | Int32
@data = ""
I suggest to generalize this syntax: instead of allowing only one of the two things, it should be possible to specify the type and the value in one line, like so:
@var : Type = value
I think this could also be useful for some macros, for example:
record Point,
x : Int32 = 0,
y : Int32 = 0
Point.new
Point.new x: 10
# etc.
Kind of a duplicate of #919, but declaring the type of a local variable is not yet supported, so this won't be supported either for local variables (at least for now, maybe in the future we can do this, shouldn't be hard)
I've syntaxed it like that in Onyx since the kick off, and can say that it feels very natural, so I often type like that by mistake all the time when coding Crystal. It should definitely be possible - it "feels like Crystal".
+1 for typing locals, can be very important in certain situations.
This is now implemented. In the next release we'll have to update some macros to take advantage of the new form, although some macros already work as one would expect :-)
class Foo
property x : Int32 = 1
end
Foo.new.x # => 1
Most helpful comment
This is now implemented. In the next release we'll have to update some macros to take advantage of the new form, although some macros already work as one would expect :-)