Kotlin无法编译此代码,因为正如编译器声明的“错误:智能转换为‘无’是不可能的,因为‘累加器’是一个复杂的表达式”。
Ye函数被称为您所期望的函数,即我想返回indexOfMax --但更重要的是理解为什么“智能cast”没有转换到accumulator an 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
}
}发布于 2017-03-20 23:27:29
这里的accumulator类型仅从初始值参数(即null )中推断。null有Nothing?类型。在检查accumulator的类型为Int之后,您可以将它的类型转换为Nothing?和Int的交集,这将导致Nothing。
这里的解决方案是显式地指定函数类型参数,或者指定参数的类型:
a.foldIndexed(null as Int?) { ...
// or
a.foldIndexed<Int?>(null) { ...https://stackoverflow.com/questions/42914434
复制相似问题