i'm trying to write a binary tree in kotlin with `...
# announcements
w
i'm trying to write a binary tree in kotlin with
Copy code
sealed 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
Copy code
Type mismatch.
Required:
BinaryTree<T>
Found:
Leaf
i'm guessing its any issue with
Nothing
? but not really sure how to work around it
e
try
class BinaryTree<out T>
by default,
<T>
is invariant: even if
T : U
, there is no relation between
Binary<T>
and
Binary<U>
with
out
,
T : U
implies
Binary<T> : Binary<U>
w
that works 🙂 i still feel confused about
in
and
out
i've read through the kdocs a few times on it but it just hasn't sunk in
e
Copy code
interface 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
Copy code
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
n
Making it out T has further implications here which you may or may not want, depends if your binary tree is read only (like List)
w
if i dont want that property what other options do i have?
n
All you really need to have a binary tree is change your Node definition to make left and right nullable Nodea
You don't need Leaf or BinaryTree
Copy code
class Node<T>(val data: T, val left: Node<T>?, val right: Node<T>?)
Commonly for convenience you would have a BinaryTree class that has a Node as its member
But it's not necessary
e
if you want a mutable tree, you can't use the same
Leaf
for every
<T>
.
at least, you can't use the same type. you can use the same instance, if you do unchecked casts on it
you can sort of imagine
null
as a singleton instance which is a
T?
for every possible
T
n
I'm not sure if that's in reference to my solution or something previous
I guess the previous, nm
e
well, it's sorta related.
Node<T> : BinaryTree<T>, Leaf : BinaryTree<T>
≅
Node<T> : Node<T>?, null : Node<T>?
the latter is what you recommended, it's definitely doable. the former only works if you give up on singleton-ness (e.g.
Leaf<T>
) or use unchecked casts