if expression in Kotlin

In this tutorial, we will learn about if expression in Kotlin. In Kotlin “if” is not a keyword(as it was in Java). In Kotlin “if” is an expression and it returns a value. In mean ordinary “If expression” in Kotlin can work just like a ternary operator(condition ? then: else) of Java. Apart from this, we can also use “if-else” as simple blocks the same as other languages(Java or c).

Example Program:

In this example, we will use “if-else” as simple blocks.

fun main(args: Array<String>) {
var num1=20
var num2=10    
var max:Int
if (num1 > num2) {
    max = num1
} else {
    max = num2
}
    println("Max is "+max)
}

Example Program:

In this example, we will use “if” as expression.

fun main(args: Array<String>) {
var num1=20
var num2=10       
   val max = if (num1 > num2) num1 else num2    
   print("Max is ="+max)
}

Example Program:

It is important “if ” expression can still return value while using as blocks the last statement of the block can be used to return value.

fun main(args: Array<String>) {
var num1=10
var num2=2    
    
   val max = if (num1>num2) {
    println("num1 is big")
    num1
    } else {
    println("num2 is big")
    num2
    }
    println("Value of max ="+max)
}

 

Spread the love
Scroll to Top