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

后端 未结 2 1691
臣服心动
臣服心动 2020-12-21 11:18

I wrote this method to apply a void function to a value and return the value.

public inline fun  T.apply(f: (T) -> Unit): T {
    f(this)
    ret         


        
2条回答
  •  囚心锁ツ
    2020-12-21 11:45

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

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

提交回复
热议问题