Hi all! There is a bunch of useful extension meth...
# announcements
j
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.
Copy code
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) }
}
n
i think to be honest it's a bit misleading, I'd avoid naming my own extension functions the same as standard library ones
If you really did want to "overload" it then you could simply make it a member function, for example
If you add
import kotlin.collections.sumOf
at the top that helps
but then the second line does not compile
j
Well, I can't overload anything in
Iterable
actually, so this is the only way I see. And naming the function not
sumOf
kills the idea of such kind of type inference.
And the reasons it doesn't work are not that obvious to me.
n
Ah right, sorry I was mixed up when I made the member function suggestion
a simpler version with an attempted fix that still does not compile
v
It’s illogical to change or to add to conventional math of common integral data types.
j
I use it not for a random data type, but for a modular arithmetics, which is a common numeric data type in ICPC: https://pl.kotl.in/k91Qv53do
v
Rustam, your IntHolder is not common integral data types ( Double, Int, Long, …). See the file _Collections.kt. When you override “sumOf”, you will get the error. If you use “fold” for calculation, change “sumOf” to “quantity” or similar for example
m
@jvmusin what does ICPC stand for?