I think it is clear that node is not null in the e...
# getting-started
m
I think it is clear that node is not null in the else brach, but the compiler forces me to use
?.
. Is there a better way to do this?
🧵 2
m
Slightly unrelated, but you probably want
node?.next = Node(content)
instead of
node?.content = content
. As for the smart-cast to
Node<T>
, the compiler probably does not do it because of the
node = node?.next
assignment in the loop. You could use the
!!
operator instead of
?.
, but I'm not sure if there is a better way.
Copy code
fun push(content: T) {
        if (first == null) {
            first = Node(content)
        } else {
            var node = first!!
            while (node.next != null) {
                node = node.next!!
            }
            node.next = Node(content)
        }
    }}
e
I would expect, that the reason for the nullability is the mutability of fields. So you do a non null check on
next
, but don't know, if a different
Thread
or whatever changes the field again between check an assignment. You might solve this by introducing an intermediate local variable to hold the value, you check against.
Copy code
class Stack<T> {
    private var first: Node<T>? = null

    fun push(content: T) {
        var h = first
        if (h == null) {
            first = Node(content)
        } else {
            var node = h
            h = h.next
            while (h != null) {
                node = h
            }
            node.content = content
        }
    }
}

class Node<T>(var content: T) {
	var next: Node<T>? = null
}
2