lambda 参数类型的类型推断
Type inference for lambda parameter types
Kotlin 无法编译此代码,因为正如编译器所述 "Error: Smart cast to 'Nothing' is impossible, because 'accumulator' is a complex expression"
旧函数的调用方式如您所料,即我想 return indexOfMax —— 但更重要的是理解 "smart cast" 无法转换为 [=12 的原因=]一个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?
和 Int
的交集,结果为 Nothing
.
这里的解决方案是显式指定函数类型参数,或者指定参数类型:
a.foldIndexed(null as Int?) { ...
// or
a.foldIndexed<Int?>(null) { ...
Kotlin 无法编译此代码,因为正如编译器所述 "Error: Smart cast to 'Nothing' is impossible, because 'accumulator' is a complex expression"
旧函数的调用方式如您所料,即我想 return indexOfMax —— 但更重要的是理解 "smart cast" 无法转换为 [=12 的原因=]一个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?
和 Int
的交集,结果为 Nothing
.
这里的解决方案是显式指定函数类型参数,或者指定参数类型:
a.foldIndexed(null as Int?) { ...
// or
a.foldIndexed<Int?>(null) { ...