I'm struggling with nullable and non-nullable types. There are two errors. I defined a class which implements the "Queue" concept, as follows, trying to make its Generic Parametric Type nullable and here there's the first error:
class QueueLightweight<T: Any?> { //: Queue<T?> removed because of Java clashes, but it's another question
protected var size = 0
protected var first: NodeQLW<T>? = null
protected var last: NodeQLW<T>? = null
protected class NodeQLW<E>(var item: E) {
var next: NodeQLW<E>? = null
}
....
fun iterator(): Iterator<T> {
return IteratorQLW(this)
}
....
fun add(e: T?): Boolean {
val n: NodeQLW<T>
n = NodeQLW(e) // <--- first error:
// "type inference failed: required: QueueLightweight.NodeQLW<T> , found: QueueLightweight.NodeQLW<T?> "
if (size == 0) {
last = n
first = last
size = 1
} else {
last!!.next = n
last = n
size++
}
return true
}
}
I then defined an Iterator subclass as follows, and in the highlighted line (by an arrow), there's the error.
protected class IteratorQLW<E: Any?>(var q: QueueLightweight<E>) :
Iterator<E> {
var n: NodeQLW<E>?
init {
n = q.first
}
override fun hasNext(): Boolean {
return n != null
}
override fun next(): E {
var e: E
e = null // <--- error here: null cannot be a value of a non-null type E
if (n != null) {
e = n!!.item
n = n!!.next
}
return e
}
}
I don't understand how to fix those errors.