【发布时间】:2020-08-29 15:13:11
【问题描述】:
在以下最小示例中,useFoos(a) 完全没问题,但useFoos(b) 给出了compiler error。
interface FooInterface
fun useFoos(foos: Array<FooInterface>) {}
enum class FooEnum : FooInterface
fun main() {
val a = FooEnum.values()
useFoos(a as Array<FooInterface>)
useFoos(a)
val b = FooEnum.values()
useFoos(b) // Error: Type mismatch: inferred type is Array<FooEnum> but Array<FooInterface> was expected
useFoos(b as Array<FooInterface>)
}
知道为什么会这样吗?如果它不是编译器错误,而是预期的行为,有人可以指出我指定/解释这种行为的地方吗?
【问题讨论】:
-
可能是因为如果在转换时检查成功,那么编译器已经知道我们下次发送该值时不会有问题。如果您使用
as?而不是as,那么智能转换是不可能的,因为您没有抛出异常,并且在下一行可能会发生类型不匹配。
标签: kotlin interface casting type-inference type-deduction