简体   繁体   English

有没有办法制作密封类 generics?

[英]Is there a way to make sealed classes generics?

How a generic result or error type could be defined in Kotlin?如何在 Kotlin 中定义通用结果或错误类型? Something like this example from TypeScript像 TypeScript 的这个例子

type Errorneous<E, R> = 
  { is_error: true, error: E } | { is_error: false, result: R }

function calculate(): Errorneous<String, Number> { 
  return { is_error: false, result: 2 }
}

The problem is that Kotlin doesn't have generic sealed classes.问题是 Kotlin 没有通用密封类。

It's possible to define something like可以定义类似的东西

data class Errorneous<E, R>(val error: E?, val result: R?)

But it not ideal as it allows wrong usage like但它并不理想,因为它允许错误使用,例如

Errorneous<String, Int>(null, null)
Errorneous<String, Int>("", 2)

UPDATE更新

Possible (not compiling) Kotlin code可能(未编译)Kotlin 代码

sealed class Errorneous
class Success<R>(val result: R) : Errorneous()
class Fail<R>(val error: R) : Errorneous()

fun calculate(): Errorneous {
  return Success(2)
}

fun main() {
  val result = calculate()
  if (result is Success<*>) { 
    val r: Int = result.result // <= Problem here, no smart cast
  }
}

You have to add generic parameters to the base class as well:您还必须将通用参数添加到基本 class 中:

sealed class Errorneous<E,R>
class Error<E,R>(val error: E): Errorneous<E,R>()
class Success<E,R>(val result: R): Errorneous<E,R>()


fun calculate(): Errorneous<String, Int> {
    return Success(2)
}

fun main() {
    val result = calculate()
    if (result is Success<*, Int>) {
        val r: Int = result.result // <= smart cast
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM