【发布时间】:2017-03-14 01:27:50
【问题描述】:
在以下代码中,"Happy Halloween!"、42 等被标记为“类型不匹配”。 (必需:T,找到:String(或 Int))但编译器不应该能够从类型检查中推断出返回值是正确的类型吗?
interface Type<T>
class StringType() : Type<String>
class IntType1() : Type<Int>
class IntType2(val a: Int, val b: Int) : Type<Int>
fun <T> something(type: Type<T>): T = when (type) {
is StringType -> "Happy Halloween!"
is IntType1 -> 42
is IntType2 -> type.a * type.a + type.b * type.b + type.a * type.b
else -> throw IllegalArgumentException()
}
【问题讨论】:
-
您已将函数的返回类型设置为
T,但您返回的是字符串Happy Halloween!。这就是你得到类型不匹配的原因。 -
@marstran 返回类型是
T但在type is StringType之后返回true我希望编译器现在知道T确实是String。 -
啊,现在我明白了
-
@marstran 这样的强制转换是不安全的,因为
is StringType -> 42 as T也会编译,这不是我想要的。我希望编译器帮助我确保返回适当的类型。 -
我认为只是 Smart Cast 不够聪明,无法推理泛型类型。我假设它只检查当前级别的类型,而不深入类型声明。
标签: kotlin