Search code examples
androidkotlinobjectanimator

Destructuring declaration initializer of type ObjectAnimator


I'm using kotlin destructuring declarations. I used it before with SpringAnimation and it worked perfectly. Now I want use it with ObjectAnimator and I get this error:

Destructuring declaration initializer of type ObjectAnimator! must have a 'component1()' function

Destructuring declaration initializer of type ObjectAnimator! must have a 'component2()' function

Here is my code:

val (xanimator, alphaanim) = findViewById<View>(R.id.imageView).let { img ->
            ObjectAnimator.ofFloat(img, "translationX", 100f).apply {
                duration = 2000
            }
            to
            ObjectAnimator.ofFloat(img, "alpha", 1.0f).apply {
                duration = 2000
            }
        }

What's wrong?


Solution

  • The issue here is that you can't start an infix call function call on a new line - the compiler essentially infers a semicolon/line ending after your first apply call. This is the same way with operators, see this issue for example.

    So you need to reformat your code a bit for the to to connect, most simply like this:

    val (xanimator: ObjectAnimator, alphaanim: ObjectAnimator) = findViewById<View>(R.id.imageView).let { img ->
        ObjectAnimator.ofFloat(img, "translationX", 100f).apply {
            duration = 2000
        } to
        ObjectAnimator.ofFloat(img, "alpha", 1.0f).apply {
            duration = 2000
        }
    }
    

    But for readability, maybe you could go with something like this:

    val (xanimator: ObjectAnimator, alphaanim: ObjectAnimator) = findViewById<View>(R.id.imageView).let { img ->
        Pair(
                ObjectAnimator.ofFloat(img, "translationX", 100f).apply {
                    duration = 2000
                },
                ObjectAnimator.ofFloat(img, "alpha", 1.0f).apply {
                    duration = 2000
                }
        )
    }
    

    Or anything inbetween.