Is there a built-in Kotlin method to use the void function for evaluation?

I wrote this method to apply the 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 for shortening something like this:

 return values.map { var other = it.toOther() doStuff(other) return other } 

Something like that:

 return values.map { it.toOther().apply({ doStuff(it) }) } 

Does Kotlin have a language function or method like this?

+2
kotlin utility-method
source share
2 answers

I ran into the same problem. My solution is basically the same as yours, with a little clarification:

 inline fun <T> T.apply(f: T.() -> Any): T { this.f() return this } 

Note that f is an extension function. This way you can reference the methods on your object using the implicit this link. Here is an example taken from my libGDX project:

 val sprite : Sprite = atlas.createSprite("foo") apply { setSize(SIZE, SIZE) setOrigin(SIZE / 2, SIZE / 2) } 

Of course, you can also call doStuff(this) .

+1
source share

Apply in the Kotlin standard library: see docs here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html

His method signature:

 inline fun <T> T.apply(f: T.() -> Unit): T (source) 

Calls the specified function f with this value as a receiver and returns this value.

+4
source share

All Articles