是否有内置的Kotlin方法将void函数应用于值?

是否有内置的Kotlin方法将void函数应用于值?

问题描述:

我编写了此方法,以将void函数应用于值并返回该值.

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
}

对于这样的事情:

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

Kotlin是否已经内置了这样的语言功能或方法?

Is there a language feature or method like this already build in to Kotlin?

我遇到了同样的问题.我的解决方案与您的解决方案基本相同,只是略有改进:

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
}

请注意,f是扩展功能.这样,您可以使用隐式this引用在对象上调用方法.这是一个来自我的libGDX项目的示例:

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

当然,您也可以致电doStuff(this).