Below code gets an
Error: undefined method '<<' for Nil (compile-time type is (Array(Node) | Nil)). The
@children is initialized on demand when it is nil in method
add_child, so the code should work. I expect the
@children should be nil when it is a leaf node by default. But it has the compiling error, how to fix this?
class Node getter children : Array(self)? = nil def initialize(@name : String) end def add_child(child : self) @children = Array(self).new if children.nil? @children << child end end Node.new("root").add_child(Node.new("a child"))