Kotlin lambda参数类型的类型推断
Kotlin未能编译此代码,因为正如编译器所述,“错误:智能转换为‘Nothing’是不可能的,因为‘accumulator’是一个复杂的表达式” Ye olde函数的调用是您所期望的,也就是说,我想返回indexOfMax——但更重要的是理解为什么“智能转换”无法转换到Kotlin lambda参数类型的类型推断,kotlin,type-inference,Kotlin,Type Inference,Kotlin未能编译此代码,因为正如编译器所述,“错误:智能转换为‘Nothing’是不可能的,因为‘accumulator’是一个复杂的表达式” Ye olde函数的调用是您所期望的,也就是说,我想返回indexOfMax——但更重要的是理解为什么“智能转换”无法转换到累加器anInt fun indexOfMax(a: IntArray): Int? { return a.foldIndexed(null) { index, accumulator, element ->
累加器anInt
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
}
}
此处的累加器的类型仅从初始值参数推断,即null
。null
的类型为Nothing?
。检查累加器
的类型是否为Int
,然后将其类型智能转换为Nothing?
和Int
的交叉点,从而导致Nothing
这里的解决方案是显式指定函数类型参数,或指定参数的类型:
a.foldIndexed(null as Int?) { ...
// or
a.foldIndexed<Int?>(null) { ...
a.foldIndexed(null为Int?{。。。
//或
a、 折叠索引(空){。。。
此处的累加器的类型仅从初始值参数null
推断。null
具有类型Nothing?
。在检查累加器的类型是否为Int
后,将其类型智能转换为Nothing?
和的交叉点t
,这将导致无效
这里的解决方案是显式指定函数类型参数,或指定参数的类型:
a.foldIndexed(null as Int?) { ...
// or
a.foldIndexed<Int?>(null) { ...
a.foldIndexed(null为Int?{。。。
//或
a、 折叠索引(空){。。。
有趣的是,您是如何发现“智能强制转换”是由类型的交集决定的?有趣的是,您是如何发现“智能强制转换”是由类型的交集决定的?