是否有可能在when语句中返回与type参数相同的类型 [英] Is it possible to return the same type as the type parameter in when statement
本文介绍了是否有可能在when语句中返回与type参数相同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
For example:
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.
}
它会产生编译错误:
It gives compile errors:
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
推荐答案
您可以将结果转换为<$之后再c $ c> T 。你不会得到任何编译器的帮助,你会得到警告,但至少它会编译:
You can cast the result to T
afterwards. You won't get any compiler assistance with that and you will get warnings, but at least it does compile:
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
请注意,当(a)这里是不必要的,当{足够时,只需。
Note that when (a)
here is unnecessary, just when {
is enough.
这篇关于是否有可能在when语句中返回与type参数相同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文