Nae*_*mul 3 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.
}
Run Code Online (Sandbox Code Playgroud)
它给出了编译错误:
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
Run Code Online (Sandbox Code Playgroud)
您可以将结果投射到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
Run Code Online (Sandbox Code Playgroud)
请注意,when (a)
这是不必要的,就when {
足够了.
归档时间: |
|
查看次数: |
122 次 |
最近记录: |