【发布时间】: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