In Kotlin, the "if" is an expression and not a statement as it is in Java. This tutorial explains why that eliminates the need for the ternary operator with Java.
- Programmers at some point, have to make a decision, to execute a block of code, or not, or to execute it once or multiple times. This is known as Control Flow. The If expression is the most basic way to control flow in Kotlin. Also note, that in Kotlin If is an expression, not a statement as it is in Java. A statement is an executed line or block of code which doesn't return a value. As a result, a statement can't sit on the right side of an equal sign.
An expression returns a value. So the result of a Kotlin If expression can be assigned to a variable. Because of this the ternary expression would be redundant and doesn't exist in Kotlin. In Java, we would write, I'm going to put this in a comment because this is Java code and it won't run on Kotlin, create a variable called lowest. We're going to say A is less than B, We're going to return, A , we're going to return B.
In Kotlin, we can write something similar using the If expression. We're going to write pretty much the same thing, only this time in Kotlin. So we're going to create a variable called lowest, we're going to say it's equal to if myInt is lower than anInt. We will return myInt else. We will return anInt.
And lets just print this out. The lowest value is lowest. This brings up an important point, when if is used as an expression it must contain an else clause. The expression must have a value in all cases. So lets to a little bit bigger of an example.
This time we're going to create a variable called temp. Set it equal to eighty. We're also going to create another variable called Is Air Conditioner On. And set that equal to the results of If temp is greater than or equal to eighty. We are going to print line and say, it is warm and we are going to return the value true.
Else... We're going to say print line and say, It is not so warm and return false. Notice that in both cases I don't have to specify return it's just the value, the last value becomes the value of the expression, and we say print line, Is the air conditioner on, and get the value of the variable.
Okay, so lets go ahead and execute this code, and we can see that the lowest value is one, that it is warm and the air conditioner is on. As in other languages both the If an Else clauses can have multiple lines, we simply need to place the code inside the curvy braces. In this contrived example, we have multi line clauses for both if and else. And we assign the results of the expression to the variable Is the air conditioner on.
- Kotlin as a better Java
- Setting up a Kotlin programming environment
- Val vs. var
- Understanding basic Kotlin programming concepts
- Object-oriented programming
- Using Java from Kotlin
- Using Kotlin from Java
- Annotations, reflection, and DSL construction
- Functional programming in Kotlin