Is there a built in Kotlin method to apply void fu

2019-01-28 16:27发布

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?

2条回答
2楼-- · 2019-01-28 17:13

I ran into the same problem. My solution is basicly the same as yours with a small refinement:

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

Note, that f is an extension function. This way you can invoke methods on your object using the implicit this reference. Here's an example taken from a libGDX project of mine:

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

Of course you could also call doStuff(this).

查看更多
看我几分像从前
3楼-- · 2019-01-28 17:21

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

Its method signature:

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

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

查看更多
登录 后发表回答