例如:
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/