在多个接收器上调用一个通用的方法
通常情况下,我有以下模式:
ax() ay() az()
Kotlin提供了一个方便的选择:
a.run { x(); y(); z() }
有时我有这样的模式:
ax() bx() cx()
我想写这样的东西:
applyTo(a, b, c) { it.x() }
所以我可能会执行以下操作:
fun applyTo(vararg ps: P, fx: (P) -> Unit) = ps.forEach { fx(it) }
或者,像这样的东西:
::x.eachOf(a, b, c)
所以我可以实现这个function:
fun ((P) -> R).eachOf(vararg p: P) = p.forEach { this(it) }
有没有办法使用标准库在多个接收器上调用共享方法,或者缩短模式#2的更好方法?
只需使用一个列表:
listOf(a, b, c).forEach { it.x() }
我假设你的a,b,c
是同一types的。 你可以修改你的applyTo
来接受一个带有接收器的lambdaexpression式,并使调用看起来像在run
:
fun applyTo(vararg ps: P, fx: P.() -> Unit) = ps.forEach { it.fx() } //call without it.x() applyTo(a, b, c) { x() }
你的第二个解决方案是有趣的,但不可读的imho。 不会这样做。