Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a "forEach" that returns an object that is a receiver to the consuming function?

Tags:

kotlin

I'm trying to do something like this in a long chain of "stream" operations.

fun main(args: Array<String>) {
    "test1, test2, test3".split(", ")
            .toCustomString(StringBuilder(), StringBuilder::append)
}

fun <T, R>Iterable<T>.toCustomString(obj: R, thing: R.(T) -> Unit): R {
    this.forEach {
        obj.thing(it)
    }
    return obj
}

But this doesn't work it says none of the functions found for StringBuilder::append can't be applied here. Is there a way I can make something like this work?

like image 585
usbpc102 Avatar asked Sep 18 '25 05:09

usbpc102


2 Answers

You are trying to use a method reference with a different signature for a receiver function. You can make it work with supplying a lambda instead. Or as other answers point out, changing the signature of your receiver function.

fun main(args: Array<String>) {
    "test1, test2, test3".split(", ")
            .toCustomString(StringBuilder(), { item -> append(item) })
}
like image 192
Marko Devcic Avatar answered Sep 19 '25 22:09

Marko Devcic


There's no problem to use a method reference in that case and it should work perfectly.

Just ensure you use kotlin class StringBuilder an change this:

fun <T, R>Iterable<T>.toCustomString(obj: R, thing: R.(T) -> Unit)

by this one:

fun <T, R>Iterable<T>.toCustomString(obj: R, thing: R.(T) -> R)

like image 45
GoRoS Avatar answered Sep 19 '25 22:09

GoRoS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!