generics - 是否可以在when语句中返回与类型参数相同的类型

标签 generics types kotlin

例如:

fun <T> f(a: T): T =
    when (a) {
        a is Int -> 0  // if T is Int, then return Int
        a is String -> ""  // if T is String, then return String
        else -> throw RuntimeException()  // Otherwise, throw an exception so that the return type does not matter.
    }

它给出了编译错误:

Error:(3, 20) The integer literal does not conform to the expected type T
Error:(4, 23) Type mismatch: inferred type is String but T was expected

最佳答案

之后您可以将结果转换为 T。你不会得到任何编译器帮助,你会收到警告,但至少它确实编译:

fun <T> f(a: T): T =
    when {
        a is Int -> 0  // if T is Int, then return Int
        a is String -> ""  // if T is String, then return String
        else -> throw RuntimeException()  // Otherwise, throw an exception so that the return type does not matter.
    } as T

注意这里的when (a)是不必要的,只要when {就足够了。

关于generics - 是否可以在when语句中返回与类型参数相同的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588620/

相关文章:

java - Android Studio 4.1 调试器断点不起作用

android - 如何在 Kotlin 中将字节附加到 ByteArray

vb.net - VB中的泛型可以访问共享数据吗?

swift - 我可以在 Swift 中将默认类型分配给泛型类型 T 吗?

generics - Rust 中使用约束泛型的函数指针

json - 如何存储参数化方法的类型参数,然后使用它们将 JSON 对象转换为泛型类型的普通对象?

c++ - 定义将对内存进行操作的函数时,将地址传递为 void* 还是 uint8* 更正确?

c++ - 创建超出其正常大小的数字数据类型

haskell - 创建一个类型,它是其他类型的子集

java - 显示对话框的软键盘