In this section, we will learn what the ternary operator is and how to use it in Kotlin.
Note: we’re assuming you’re already familiar with the Kotlin if statement.
What is Ternary Operator in Kotlin?
The ternary operator is a short way of evaluating a condition that results either true or false and then returns a value based on the result of the condition.
Be aware that in Kotlin, there’s no specific syntax for the ternary operator! It’s just the if else statement but in shorter syntax.
Basically, the if-else statements can be used as an expression that is capable of returning a value. So we use this capability to evaluate a value (the condition) and then, based on the evaluation, return a result.
Let’s get into the syntax section and then we will continue our discussions on how to use the ternary operator.
Kotlin Ternary Operator Declaration Syntax:
var result = if (condition) true_expression else false_expression
if(condition)
: this is the condition that we first need to define and it will be evaluated first.
true_expression
: this expression will be run only if the result of the condition we’ve set was true.
Also note that the result of the true_expression
will be returned after evaluation.
false_expression
: this expression will be run only if the result of the condition we’ve set for the if statement was false. Also, the result of this expression will return and can be stored in a variable.
Example: using ternary operator in Kotlin
fun main(){ var developer = "Java" var apply = if (developer =="Java" || developer == "Kotlin") "You can apply for a job here" else "You can't apply for a job here unfortunately" println(apply) }
Output:
You can apply for a job here
How Does Ternary Operator Work in Kotlin?
Here, the condition of the if statement is to see if the value of the developer variable is equal to either “Java” or “Kotlin”. Now because the variable’s value is equal to “Java”, then the result of the condition is true and so the true_expression
which is just the simple text message, ran and is returned to be stored in the apply
variable. After that, this message is sent to the output stream using the println() function.