Null object: Difference between revisions

Added Crystal example
(Added Tailspin solution)
(Added Crystal example)
Line 541:
END ObjectNil.
</lang>
 
=={{header|Crystal}}==
In Crystal, nil is represented by an instance of the Nil type, accessed by the identifier <code>nil</code>. A variable can only become nil if Nil is one of its possible types. All objects inheriting from the base Object class implement the method <code>.nil?</code> which returns true if the object is nil and false if it isn't. The equality and case equality operators can also be used to check for nil. The compiler returns an error if an object may be nil but is not treated as such. This can be suppressed with the <code>.not_nil!</code> method, which throws an exception at runtime if the object is in fact nil.
<lang crystal>foo : Int32 | Nil = 5 # this variable's type can be Int32 or Nil
bar : Int32? = nil # equivalent type to above, but shorter syntax
baz : Int32 = 5 # this variable can never be nil
 
foo.not_nil! # nothing happens, since 5 is not nil
puts "Is foo nil? #{foo.nil?}"
foo = nil
puts "Now is foo nil? #{foo.nil?}"
 
puts "Does bar equal nil? #{bar == nil}"
 
puts "Is bar equivalent to nil? #{bar === nil}"
 
bar.not_nil! # bar is nil, so an exception is thrown</lang>
{{out}}
<pre>Is foo nil? false
Now is foo nil? true
Does bar equal nil? true
Is bar equivalent to nil? true
Unhandled exception: Nil assertion failed (NilAssertionError)
...</pre>
 
 
=={{header|D}}==
Anonymous user