Kotlin if Expression

In Kotlin, if is an expression, i.e. it returns a value. herefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.


Traditional if in Kotlin

if can used in same way like java programming.

mport java.util.*

fun main(array: Array<String>) {

    var sc: Scanner = Scanner(System.`in`)


    println("Enter the number : ")

    var n: Int = sc.nextInt();

    if (n.rem(2) == 0) {
        println("Even number")
    } else {
        println("Odd number")
    }

}
Enter the number : 
21
Odd number

as expression


fun main(array: Array<String>) {

    var a: Int = 5
    var b: Int = 6

    var max: Int = if (a > b) a else b

    println("max is ${max}")
}
max is 6

if branches can be blocks, and the last expression is the value of a block:

fun main(array: Array<String>) {

    var a: Int = 5
    var b: Int = 6

    var max: Int = if (a > b) {
        println("A is greater")
        a
    } else {
        println("b is greater")
        b
    }

    println("Max is ${max}")
}
b is greater
Max is 6
woman avatar