Why isn't there a mass apply function in the standard library?


#1

I often need to apply the same function on multiple variables (especially in Android), so why isn’t there something like apply(var1, var2, var3, function)?
If I had to write it, it would be something like this:

fun<T> apply(vararg args:T?, func: T.() -> Unit){
    for (each in args){
        each?.func()
    }
}

So this way, writing something like

var1.setVisibility(Visibility.GONE)
var2.setVisibility(Visibility.GONE)
var3.setVisibility(Visibility.GONE)
var4.setVisibility(Visibility.GONE)

would be much cleaner:

apply(var1, var2, var3, var4) {
setVisibility(Visibility.GONE)
}


#2

I do like the suggestion but as a workaround that’s as many lines of code you could also write:

listOf(var1, var2, var3, var4).forEach { v ->
    v.setVisibility(Visibility.GONE)
}