Kotlin中的代数数据类型 [英] Algebraic data types in Kotlin

查看:82
本文介绍了Kotlin中的代数数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在Kotlin中使用代数数据类型,所以我试图通过以下方式实现基本的BinaryTree类型.

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<T>{
  class Node<T>(val left: Tree<T>, val right: Tree<T>): Tree<T>()
  class Leaf<T>(val value: T): Tree<T>()
}

这很好,让我构造以下树:

This is all fine, and lets me construct the following tree:

val myTree1: Tree<Int> = Node(Leaf(4), Leaf(2))

但是我也想拥有一个空"类型,所以我可以表达以下内容:

However I would like to have an "Empty" type as well, so I can express the following:

val myTree1: Tree<Int> = Node(Node(Leaf(4), Leaf(3)), Empty)

我尝试了以下操作:

sealed class Tree<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()
}

尽管我得到错误,认为对象Empty的类型参数是空的:Tree(),这实际上是很合逻辑的.

Though I get the error that Type argument is expected at object Empty: Tree(), which is actually quite logical.

我尝试过

object Empty: Tree<T>()

但是它导致未解决的参考:T".作为最后的选择,我尝试写作

But it resulted in "Unresolved reference: T". As a last resort, I tried writing

object Empty<T>: Tree<T>()

但是编译器会说对象不允许使用类型参数"

But the compiler says "Type parameters are not allowed for objects"

有没有办法在Kotlin中表达这一点?空应该是一个单例,这就是为什么它应该是一个对象.通过将其设为一个类,可以解决编译器问题,但随后必须在其后加上括号,例如=> Empty().同样,它创建不必要的对象,而实际上它应该是单例值.

Is there a way to express this in Kotlin? Empty should be a singleton, this is why it should be an object. By making it a class, it solves the compiler problems, but then I have to put parentheses after it like that => Empty(). Also, it creates unnecessary objects, while it really should be a singleton value.

在此问题上的任何帮助,我们将不胜感激. :)

I'd appreciate any help on this issue. :)

推荐答案

首先,您需要将T设置为out参数.然后,您可以将Nothing用作Empty的类型参数.

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是Kotlin中的一种特殊类型,不能具有实例,并且是所有其他类型的子类型.所以我想说这与Kotlin类型层次结构中的Any相反.

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.

这篇关于Kotlin中的代数数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆