This page topics close

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.

    Example)
    drag_handle
     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")
        }
    
    }
    Output:
    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}")
    }

    Output:
    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}")
    }

    Output:
    b is greater
    Max is 6
    
Point to remember

If you're using if as an expression rather than a statement (for example, returning its value or assigning it to a variable), the expression is required to have an else branch.

What next?

The next topic is Kotlin When Expression

Share this page