Home » Android » Strange behavior using Java ternary operator on Android

Strange behavior using Java ternary operator on Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I don’t know why but I am getting this strange error when I use a ternary operator on this example :

Screenshot of the strange behavior of setInterpolator

I think it’s related to the way that Java cast the result from the operator but it only happen in some specific cases.

Thanks for any explanation.

Note : I searched for one but could only find NPE related answers.

-Edit-

The app uses :

  • compileSdkVersion 23
  • buildToolsVersion ‘23.0.2’
  • minSdkVersion 14
  • targetSdkVersion 23
  • Android Support Library 23.2.0

Test done on Android Studio 2.0 Beta 5 with the corresponding gradle version

How to&Answers:

The reason is because of the way ternary operators work.

It always casts both the Objects to it’s nearest Super type common for both the objects.
In your case it’s BaseInterpolator, because your targetSDK version is set to 23.

But, since your minSDK is 14, the cast will not work on all the devices. Hence the error.

To fix, you can add an explicit cast of TimeInterpolator to both the objects.

Answer:

I fix this by code follow:

public class MyDecelerateInterpolator implements Interpolator {

    private DecelerateInterpolator interpolator = null;

    public MyDecelerateInterpolator() {
        interpolator = new DecelerateInterpolator();
    }

    public MyDecelerateInterpolator(float factor) {
        interpolator = new DecelerateInterpolator(factor);
    }

    @Override
    public float getInterpolation(float input) {
        return interpolator.getInterpolation(input);
    }
}