concept Tree class in category kotlin

appears as: The Tree class, Tree class
The Joy of Kotlin

This is an excerpt from Manning's book The Joy of Kotlin.

Listing 10.1 The minimal Tree implementation
sealed class Tree<out A: Comparable<@UnsafeVariance A>> {    #1    #2  

    abstract fun isEmpty(): Boolean

    internal object Empty : Tree<Nothing>() {    #3  

        override fun isEmpty(): Boolean = true

        override fun toString(): String = "E"    #4  
    }

    internal class T<out A: Comparable<@UnsafeVariance A>>(
                           internal val left: Tree<A>,    #5    #6  
                           internal val value: A,
                           internal val right: Tree<A>) : Tree<A>() {

        override fun isEmpty(): Boolean = false

        override fun toString(): String =
                    "(T $left $value $right)"    #4  
    }

    companion object {

        operator fun <A: Comparable<A>> invoke(): Tree<A> =
                                        Empty    #8  
    }
}

#1   The Tree class is parameterized, and the parameter type must extend Comparable.
#2   The Tree class is covariant on A, but the Comparable interface is contravariant, so you must deal with that.
#3   The empty tree is represented by a singleton object parameterized with Nothing.
#4   The toString functions are minimal implementations to help see the content of a tree.
#5   The T subclass represents a non-empty tree.
#6   All properties are internal so that they can’t be accessed directly from other modules.
#8   The invoke function returns the Empty singleton.