breandan
breandan

Reputation: 2024

Invoking a common method on multiple receivers

Often, I have the following pattern:

a.x()
a.y()
a.z()

Kotlin offers a convenient alternative:

a.run { x(); y(); z() }

Sometimes I have a pattern like this:

a.x()
b.x()
c.x()

I want to write something like this:

applyTo(a, b, c) { it.x() }

So I might implement the following:

fun <P> applyTo(vararg ps: P, fx: (P) -> Unit) = ps.forEach { fx(it) }

Or alternately, something like this:

::x.eachOf(a, b, c)

So I could implement the function:

fun <P, R> ((P) -> R).eachOf(vararg p: P) = p.forEach { this(it) }

Is there a way to invoke a shared method on multiple receivers using the standard library, or a better way to shorten Pattern #2?

Upvotes: 3

Views: 422

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 82007

I assume your a,b,c are of the same type. You can modify your applyTo to accept a lambda with receiver and make the call look like in run:

fun <P> applyTo(vararg ps: P, fx: P.() -> Unit) = ps.forEach { it.fx() }
//call without it.x()
applyTo(a, b, c) { x() }

Your second solution is interesting but not very readable imho. Would not do that.

Upvotes: 4

voddan
voddan

Reputation: 33819

Just use a list:

listOf(a, b, c).forEach { it.x() }

Upvotes: 4

Related Questions