'Is there any APIs that applys the same thing into different views in Kotlin?

I have 3 buttons that has the same animation.

let's call them, button1, button2, button3.

button1
    .animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
button2
    .animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
button3
    .animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()

But this is too long. I need something like...

with(button1+button2+button3).apply{
    this.animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
}

This will be clearer and simpler. I could make a list of the views but this method is also longer and massier.

Is there any features like that in Kotlin?



Solution 1:[1]

val buttons = listOf(button1, button2, button3)
buttons.forEach { 
    it.animate()
    .setDuration(initialTime)
    .setInterpolator(DecelerateInterpolator())
    .alpha(1f)
    .start()
}

Solution 2:[2]

extension function

fun Button.setUp() {
    this.animate()
        .setDuration(initialTime)
        .setInterpolator(DecelerateInterpolator())
        .alpha(1f)
        .start()
}
button1.setUp()
button2.setUp()
button3.setUp()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabe Sechan
Solution 2 GHH