0

newTilt = (newTilt > 90) ? 90 : newTilt;

What does this line of code mean? It's the first time that I see something like this in Android.

This is the full method that contains the line above:

public void onTiltMore(View view) {
    if (!checkReady()) {
        return;
    }

    CameraPosition currentCameraPosition = mMap.getCameraPosition();
    float currentTilt = currentCameraPosition.tilt;
    float newTilt = currentTilt + 10;

    newTilt = (newTilt > 90) ? 90 : newTilt;

    CameraPosition cameraPosition = new CameraPosition.Builder(currentCameraPosition)
            .tilt(newTilt).build();

    changeCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
CompuChip
  • 9,143
  • 4
  • 24
  • 48

3 Answers3

6

It is a ternary expression. It says that if the newTilt at that point is above 90, it sets it to 90, otherwise it leaves it unchanged. You could kind of think of it in the way of an if-else statement.

 if(newTilt > 90) {
    newTilt = 90;
 } else {
    newtilt = newTilt; // which does nothing useful 
 }
CompuChip
  • 9,143
  • 4
  • 24
  • 48
Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
2

This expression means that

newTilt = (newTilt > 90) ? 90 : newTilt;

is an expression which returns one of two values, 90 or newTilt. The condition, (newTilt > 90), is tested. If it is true the first value, 90 , is returned. If it is false, the second value, newTilt, is returned. Whichever value is returned is dependent on the conditional test, (newTilt > 90)

1

It's as someone has already said, it's called a ternary expression. It's something that you should really learn as I've seen it appear on quite a few interview questions. What this expression does, is if the expression evaluates to true then the left-side of the colon is used as the result and if it evaluates to false, then the right side is used. It's very often used as a shortcut to an if/else statement. In fact, you could write the above like this:

if (newTilt > 90)
    newTilt = 90;
else
    newTilt = newTilt;

Obviously, you don't need the else statement above, as newTilt doesn't change if it's less than 90. I'm just trying to show you how the ternary works.

In fact, a ternary is still a conditional expression.

int var = (expression) ? true value : false value;

Since the false condition actually does nothing, the above ternary would be better written as simply:

if (newTilt > 90)
    newTilt = 90;

That's all you need.

The Welder
  • 916
  • 6
  • 24