是否有内置的Kotlin方法将void函数应用于值? [英] Is there a built in Kotlin method to apply void function to value?
本文介绍了是否有内置的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)
.
这篇关于是否有内置的Kotlin方法将void函数应用于值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文