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?
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) })
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With