January 2019
Intermediate to advanced
246 pages
5h 23m
English
How do you declare a variable that’s of a certain type but can also be nil, sometimes called nilable? You saw earlier that in certain situations, Crystal will assign a union type to an object at compile time. You could declare a nilable type as a union type, but you can also declare its type with a ? appended, as shown here:
| | n : Int32 | Nil |
| | n = 42 |
| | p typeof(n) # => Int32 |
| | |
| | a : Int32? |
| | a = 42 |
| | p typeof(a) # => Int32 |
| | |
| | b : Int32? |
| | b = nil |
| | p typeof(b) # => Nil |
| | |
| | a.try { p a + 1 } # => 43 |
| | b.try { p b + 1 } # => no error! |
When using nilable types, the try method can come in handy: the compiler won’t signal any errors when the value might be nil. But be aware that if you lock ...
Read now
Unlock full access