Algebraic data types in Kotlin

前端 未结 1 608
粉色の甜心
粉色の甜心 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<out T>{
      class Node<T>(val left: Tree<T>, val right: Tree<T>): Tree<T>()
      class Leaf<T>(val value: T): Tree<T>()
      object Empty: Tree<Nothing>()
    }
    

    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)
提交回复
热议问题