为lambda参数类型输入推断

Kotlin无法编译此代码,因为编译器指出“Error:Smart cast to'Nothing'是不可能的,因为'accumulator'是一个复杂的表达式”

你的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 } } 

这里accumulator的类型只是从初始值参数中推断出来的,它是null 。 那个null类型是Nothing? 。 在检查accumulator的类型是否为Int ,将其类型智能化为Nothing?的交集Nothing?Int ,结果是Nothing

这里的解决方案是明确地指定函数类型参数,或者指定参数的类型:

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