【问题标题】:Type deduction fails for array of enum interface枚举接口数组的类型推导失败
【发布时间】: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


【解决方案1】:

正如@IR42 在a comment 中解释的那样,这是因为smart casts

使用out keyword 有助于使其在不强制转换的情况下工作。

更正的代码:

interface FooInterface

fun useFoos(foos: Array<out FooInterface>) {}

enum class FooEnum : FooInterface

fun main() {
    val a = FooEnum.values()
    useFoos(a as Array<FooInterface>)
    useFoos(a)

    val b = FooEnum.values()
    useFoos(b)
    useFoos(b as Array<FooInterface>)
}

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2012-03-13
    • 2020-11-28
    • 2017-02-14
    相关资源
    最近更新 更多