https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

nkiesel

08/26/2021, 8:35 PM
I get an "ERROR Overload resolution ambiguity" for
(1..10).sumOf { if (it % 2 == 0) 1 else 0 }
. This looks like a bug to me (I tried both 1.5.21 and 1.5.30). I can avoid that using e.g.
(1..10).sumOf { if (it % 2 == 0) 1L else 0L }
or
(1..10).sumOf { if (it % 2 == 0) 1.toInt() else 0.toInt() }
, but the first one produces a
Long
instead of an
Int
and the 2nd one is just ugly.
in the meanwhile, if you can supply the type through context, e.g.
Copy code
val sum: Int = sumOf { ... }
that will work
n

nkiesel

08/26/2021, 9:39 PM
thanks for the YouTrack link. However,
val sum: Int = (1..10).sumOf { if (it % 2 == 0) 1 else 0 }
still fails with the same error. My personal belief is that the decision to support automatic promotions from
Int
literals to
Long
is a design mistake in Kotlin. Kotlin normally (and rightfully so) requires explicit conversions in all other places. So why then should I be allowed to use
val l: Long = 1
and not be forced to use
val l: Long = 1L
?
e

ephemient

08/26/2021, 9:53 PM
it's not an automatic promotion, it's that integer literals are a special subtype of all built-in integer types that they would fit in. https://kotlinlang.org/spec/type-system.html#subtyping-for-integer-literal-types
15 Views