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

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)

nha*_*man 6

您可以将结果投射到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 {足够了.

  • 你也可以写`when(a)`,在每种情况下只写`is Int - >`.你不会以这种方式为每个案例重复"a". (2认同)