This post talks about how to write a ternary conditional operator with examples from Kotlin

In Java, ternary operators are written with the following syntax

condition? true_block? false_block

condition is evaluated and executes true_block if true, else false_block is executed.

There are no conditional operators in Kotlin. We can use conditional expressions such as if, when and try syntax

Kotlin Ternary Conditional Operator examples

  • Using if blocks

We can write a simplified version in a single statement.

if (conditional_expression) block1 else block2

Conditional expressions are evaluated, executes block1 if the condition is true, else block2 is executed. For example,

val number = -20
 if(number>0) "+ve" else "-ve"

assign the if expressions to a variable,

val number = -20
var numberString = if(number>0) "+ve" else "-ve"

java does not allow assigning if the expression results in a variable.

  • using when

when used to construct the similarity of if and else blocks in a readable way. Here is a syntax

when(condition) {
    expression1 -> block1
    expression2 -> block2

Here is an example

val number =1
when (number) { 
    1 -> print("1") 
    0 -> print("0") 
    else -> {  
        print("Not 0 and 1") 
  • using the Elvis operator for checking nullable variables

This is useful for null checking with simplified expressions. variable1 =variable2 ?: value

the left side of the ?: operator is a variable or expression and checked for null, if it is not null, return it,else return the right side of ?: i.e value.

if variable 2 is not null, return variable2 if variable2 is null, returns value.

Here is an example

val a=null
val b=20;
val c= a ?: b

Same can be written using below

vale c=if ( a != null ) a else b