Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior using Java ternary operator on Android

Tags:

java

android

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

like image 627
LucasFM Avatar asked Feb 25 '16 16:02

LucasFM


People also ask

Why ternary operator should not be used?

They simply are. They very easily allow for very sloppy and difficult to maintain code. Very sloppy and difficult to maintain code is bad. Therefore a lot of people improperly assume (since it's all they've ever seen come from them) that ternary operators are bad.

What is ternary operator in Android?

The ternary operator consists of a condition that evaluates to either true or false , plus a value that is returned if the condition is true and another value that is returned if the condition is false .

Is Java ternary operator lazy?

It's worth mentioning that the operator is lazy in the sense that only the used expression is evaluated: The ternary operator will not evaluate the unused branch.

What is a ternary operator in Java have you used it?

Java ternary operator is the only conditional operator that takes three operands. It's a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators.


1 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.

like image 86
Codebender Avatar answered Sep 26 '22 15:09

Codebender