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

时光总嘲笑我的痴心妄想 提交于 2019-11-29 16:09:51

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).

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!