Hello, new guy here. I’m playing with the language a little bit and I’ve decided to implement some data structures. While implementing Linked lists I’ve stomped upon strange behavior. How is that compiler can’t recognize
@tail as not
class LinkedList(V) getter head : Node(V)? getter tail : Node(V)? ... # Pushes new node value on the end of the list def push(value : V) if @head.nil? @head = Node.new(value) @tail = @head elsif !@tail.nil? @tail.next = Node.new(value) @tail = @tail.next end end end
function doesn’t compile and returns
In linked_list.cr:63:13 63 | @tail.next = Node.new(value) ^--- Error: undefined method 'next=' for Nil (compile-time type is (LinkedList::Node(Int32) | Nil))
I’ve eventually fixed it with
.not_nil! method but I was wondering how the mechanism behind null reference checks actually works and what are the best practices?