Is there a built in Kotlin method to apply void function to value? -


i wrote method apply void function value , return value.

public inline fun <t> t.apply(f: (t) -> unit): t {     f(this)     return } 

this useful in reducing this:

return values.map {     var other = it.toother()     dostuff(other)     return other } 

to this:

return values.map { it.toother().apply({ dostuff(it) }) } 

is there language feature or method build in kotlin?

i ran same problem. solution basicly same yours small refinement:

inline fun <t> t.apply(f: t.() -> any): t {     this.f()     return } 

note, f extension function. way can invoke methods on object using implicit this reference. here's example taken libgdx project of mine:

val sprite : sprite = atlas.createsprite("foo") apply {     setsize(size, size)     setorigin(size / 2, size / 2) } 

of course call dostuff(this).


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -