https://play.crystal-lang.org/#/r/78lv
class Foo
getter! name : String = "Jim"
end
There was a problem expanding macro 'getter!'
Called macro defined in macro 'macro_139694884568576'
223 | macro getter!(*names)
Which expanded to:
> 1 |
> 2 |
> 3 | @name : String = "Jim"?
> 4 |
> 5 |
> 6 |
> 7 | def name?
> 8 | @name
> 9 | end
> 10 |
> 11 | def name
> 12 | @name.not_nil!
> 13 | end
> 14 |
> 15 |
Error: expecting token ':', not 'def'
Looks like it's adding the ? incorrectly.
What's the use case for this? The idea of the bang versi贸n is that it starts nil and so you must set it before using it. Having a default value means it will never be nil so it's just like a regular property.
The main use case I was thinking of was for Granite ORM. Since the bang version defines them nilable by default and also provides methods to get the value as either nilable or not nilable it seems like the perfect thing for an ORM. Since if the user defines their column with a not nilable type, I could simply use property!, or if it's nilable, then property.
So, tl;dr it just provides a common "interface" between property and property!.
But for me it's misleading. property! means if it's not set then it will raise. If property! allows a default value then it will never raise. And at that point you better use property. Because if a user reads property! in the source code they will think "This can raise" when in fact it'll never happen.
At least with the initial value, doing something like
class Foo
property! name : String? = "Jim"
end
f = Foo.new
f.name # => "Jim"
f.name = nil
f.name # => Error
would still raise.
I could go either way, dont feel too strongly about it one way or another.
Yes, except that property! expects a non-nilable type:
class Foo
property! name : String
end
and when you do that you can't re-set the property to nil: https://play.crystal-lang.org/#/r/78pd
though maybe it should be possible to reset it to nil, I'm not sure.
I don't have any more opinions here, I'll let others comment and then we can decide.
I agree with @asterite: I fail to see the point.
馃憤
Most helpful comment
What's the use case for this? The idea of the bang versi贸n is that it starts nil and so you must set it before using it. Having a default value means it will never be nil so it's just like a regular property.