【问题标题】:Type inference for lambda parameter typeslambda 参数类型的类型推断
【发布时间】:2017-03-20 21:38:38
【问题描述】:

Kotlin 无法编译此代码,因为编译器指出“错误:智能转换为 'Nothing' 是不可能的,因为 'accumulator' 是一个复杂的表达式”

Ye olde 函数被称为您所期望的,即我想返回 indexOfMax ——但更重要的是理解为什么“智能转换”无法转换为 accumulator 和 Int

fun indexOfMax(a: IntArray): Int? {
    return a.foldIndexed(null) { index, accumulator, element ->
        return if (accumulator is Int) {
            var i:Int = accumulator
            return if (accumulator == null) index
                   else if (element > a[i]) index
                   else accumulator
        } else accumulator
    }
}

编辑

是的,接受的答案有效!这是解决方案:

fun indexOfMax(a: IntArray): Int? {
    return a.foldIndexed(null as Int?) { index, accumulator, element ->
        if (accumulator == null) index
            else if (element >= a[accumulator]) index
            else accumulator
    }
}

【问题讨论】:

    标签: kotlin type-inference


    【解决方案1】:

    这里accumulator的类型仅从初始值参数推断,即null。 null 的类型为 Nothing?。检查accumulator 的类型为Int 后,将其类型智能转换为Nothing? 和Int 的交集,从而得到Nothing。

    这里的解决方案是显式指定函数类型参数,或者指定参数的类型:

    a.foldIndexed(null as Int?) { ...
    // or
    a.foldIndexed<Int?>(null) { ...
    

    【讨论】:

    • 有趣,您是如何发现“智能类型转换”是由类型的交集决定的?
    猜你喜欢
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多