Hi all!
There is a bunch of useful extension methods in Kotlin 1.4 like
kotlin.collections.sumOf
.
I find it very useful, but I have a use case when I want to overload this function.
Suppose I have a simple class
IntHolder
and an extension function
Iterable<T>.sumOf((T) -> IntHolder)
.
How can I use both mine
sumOf
and prewritten
sumOf
from
kotlin.collections
?
I have some workarounds like renaming this method or using
import as
for a
kotlin.collections.sumOf
, but those are not solutions, but just workarounds.
Maybe you know the reason it doesn't work or you know how to make it work?
As for me, right now it looks like a bug.
I've already asked about this on StackOverflow but got no responses
Here.
The real use case is actually not that simple, but I believe the code below totally describes the whole situation.
import kotlin.experimental.ExperimentalTypeInference
data class IntHolder(val x: Int) {
operator fun plus(other: IntHolder) = IntHolder(x + other.x)
}
@OptIn(ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
inline fun <T> Iterable<T>.sumOf(f: (T) -> IntHolder) = fold(IntHolder(0)) { acc, i -> acc + f(i) }
fun main() {
val range = 1..5
val a = range.sumOf { it * 2 } //here is an error
val b = range.sumOf { IntHolder(it * 2) }
}