I wrote this method to apply a void function to a value and return the value.
public inline fun <T> T.apply(f: (T) -> Unit): T {
f(this)
return this
}
This is useful in reducing something like this:
return values.map {
var other = it.toOther()
doStuff(other)
return other
}
To something like this:
return values.map { it.toOther().apply({ doStuff(it) }) }
Is there a language feature or method like this already build in to Kotlin?
I ran into the same problem. My solution is basicly the same as yours with a small refinement:
Note, that
f
is an extension function. This way you can invoke methods on your object using the implicitthis
reference. Here's an example taken from a libGDX project of mine:Of course you could also call
doStuff(this)
.Apply is in the Kotlin standard library: See the docs here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html
Its method signature: