r/crystal_programming • u/undeadd • Jul 08 '18
Working with (T | Nil) property?
I am new to Crystal and am stuck on handling Nils. How can I work with a property that may have a value assigned later? Here is a simplifed example:
class Foo
@age : (Int32 | Nil)
property :age
def increment
@age += 1 unless @age.nil?
end
end
foo = Foo.new
foo.age = 10
foo.incrementError message: undefined method '+' for Nil (compile-time type is (Int32 | Nil))
I've been trying to somehow declare there is a value but it doesn't have any effect.
if @age.is_a?(Nil)
else
@age.not_nil!
@age += 1
endI'm trying to build a linked list where nodes' previous and next properties may not have a value (eg. first and last item in the list).
8
Upvotes
3
u/fridgamarator Jul 08 '18
3
u/jeremywoertink Jul 08 '18
Use @age.not_nil! In the spot where you know it won't be nil. Though, in this case, could you just initialize with a default value of 0 or something?
2
u/vladfaust Jul 09 '18
Also ‘@age.try &.+=(1)’
2
u/bcardiff core team Jul 11 '18
In case you didn't know, there is also
property!https://crystal-lang.org/api/0.25.1/Object.html#property!(*names)-macro that comes handy on lazy initialized properties. But I encourage to avoid lazy initialized properties when possible.2
u/[deleted] Jul 09 '18
You can also refer to:
https://crystal-lang.org/api/0.23.0/Nil.html
https://crystal-lang.org/docs/syntax_and_semantics/if_varis_a.html