Algebraic data types in Kotlin

前端 未结 1 612
粉色の甜心
粉色の甜心 2021-02-02 14:38

I am trying to figure out how to use algebraic data types in Kotlin, so I\'m trying to implement a basic BinaryTree type the following way.

sealed class Tree<         


        
1条回答
  •  佛祖请我去吃肉
    2021-02-02 14:47

    First you need to make T an out parameter. Then you can use Nothing as a type argument for Empty.

    sealed class Tree{
      class Node(val left: Tree, val right: Tree): Tree()
      class Leaf(val value: T): Tree()
      object Empty: Tree()
    }
    

    Nothing is a special type in Kotlin, which cannot have an instance and is a subtype of all other types. So I would say it's opposite to Any in Kotlin type hierarchy.

    0 讨论(0)
提交回复
热议问题