在下面的代码中:
Kotlin出现以下错误:
如果我显式地使用
为什么 Kotlin 没有自动使用
val sum = listOf(1, 2, 3).sumOf { if (it % 2 == 0) 1 else 0 }
Kotlin出现以下错误:
Kotlin: Overload resolution ambiguity:
public inline fun <T> Iterable<TypeVariable(T)>.sumOf(selector: (TypeVariable(T)) -> Int): Int defined in kotlin.collections
public inline fun <T> Iterable<TypeVariable(T)>.sumOf(selector: (TypeVariable(T)) -> Long): Long defined in kotlin.collections
如果我显式地使用
toInt()
,错误就会消失,但我会收到一个冗余调用的警告。
val sum = listOf(1, 2, 3).sumOf { if (it % 2 == 0) 1.toInt() else 0 }
为什么 Kotlin 没有自动使用
Int
类型?
val sum = listOf(1, 2, 3).sumOf { 1 - it % 2 }
。然而,(1)我不太确定为什么它可以工作而原始代码不能;(2)不幸的是,这不是你问题的通用解决方案。 - Klitos Kyriacouif (it % 2 == 0) 1 else 0
能明确地解析为一个整数。 - Tenfour041 - it % 2
在这里无法帮助。我拥有的是像list.sumOf { if(someCondition) x else y }
这样的东西,其中 x 和 y 是通常的整数。 - Arpit Shukla