william
11/15/2020, 5:28 PMsealed class BinaryTree<T> {
val root: BinaryTree<T> = Leaf
}
data class Node<T>(val data: T, val left: BinaryTree<T>, val right: BinaryTree<T>) : BinaryTree<T>()
object Leaf : BinaryTree<Nothing>()
can anyone help my understand why root: BinaryTree<T> = Leaf
gives the error
Type mismatch.
Required:
BinaryTree<T>
Found:
Leaf
william
11/15/2020, 5:29 PMNothing
? but not really sure how to work around itephemient
11/15/2020, 5:33 PMclass BinaryTree<out T>
ephemient
11/15/2020, 5:34 PM<T>
is invariant: even if T : U
, there is no relation between Binary<T>
and Binary<U>
ephemient
11/15/2020, 5:35 PMout
, T : U
implies Binary<T> : Binary<U>
william
11/15/2020, 5:35 PMin
and out
i've read through the kdocs a few times on it but it just hasn't sunk inephemient
11/15/2020, 5:44 PMinterface Producer<out T> {
fun produce(): T
}
var p: Producer<Number>
p = object : Producer<Int> // p.produce() is Number, OK
p = object : Producer<Any> // p.produce !is Number, NOT OK
interface Consumer<in T> {
fun consume(t: T)
}
val t: Number = 0.toFloat()
var c: Consumer<Number>
c = object : Consumer<Any> // p.consume(t) OK
c = object : Consumer<Int> // p.consume(t) NOT OK
Nir
11/15/2020, 5:46 PMwilliam
11/15/2020, 5:46 PMNir
11/15/2020, 5:47 PMNir
11/15/2020, 5:47 PMNir
11/15/2020, 5:49 PMclass Node<T>(val data: T, val left: Node<T>?, val right: Node<T>?)
Nir
11/15/2020, 5:51 PMNir
11/15/2020, 5:51 PMephemient
11/15/2020, 5:55 PMLeaf
for every <T>
.ephemient
11/15/2020, 5:58 PMephemient
11/15/2020, 5:59 PMnull
as a singleton instance which is a T?
for every possible T
Nir
11/15/2020, 6:08 PMNir
11/15/2020, 6:10 PMephemient
11/15/2020, 6:22 PMNode<T> : BinaryTree<T>, Leaf : BinaryTree<T>
≅ Node<T> : Node<T>?, null : Node<T>?
ephemient
11/15/2020, 6:24 PMLeaf<T>
) or use unchecked casts