jvmusin
12/01/2020, 4:05 PMkotlin.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) }
}
Nir
12/01/2020, 4:11 PMNir
12/01/2020, 4:12 PMNir
12/01/2020, 4:14 PMimport kotlin.collections.sumOf
at the top that helpsNir
12/01/2020, 4:14 PMjvmusin
12/01/2020, 4:16 PMIterable
actually, so this is the only way I see. And naming the function not sumOf
kills the idea of such kind of type inference.jvmusin
12/01/2020, 4:16 PMNir
12/01/2020, 4:17 PMNir
12/01/2020, 4:21 PMNir
12/01/2020, 4:21 PMVal Salamakha
12/02/2020, 4:22 AMjvmusin
12/02/2020, 9:23 AMVal Salamakha
12/02/2020, 9:00 PMMatteo Mirk
12/15/2020, 7:54 AM