IF as Expression

If Condition and If Expression

IF Condition

In Kotlin we can use If statement as condition as well as expression, If condition is like our traditional usage in java.

 fun main(args:Array<String>)
{
    var a=5    var b=10        if (a>b)
    {
        print("Max value is $a")
    }
    else if (a<b)
    {
        print("Max value is $b")
    }
    else    {
        print("both are equal")
    }
}


Output:
Max value is 10

If Expression

In kotlin if is an expression. ie: It returns a value
fun main(args:Array<String>)
{
    var a=5    var b=10
    var max=if (a>b)
    {
        a
    }
    else if (a<b)
    {
        b
    }
    else    {
        "both are equal"    }

    print("max value is $max")
}

Output: Max value is 10
The if expression has block of statements it will return the last statement as expression value
fun main(args:Array<String>)
{
    var a=5    var b=10
    var max=if (a>b)
    {
        println("a is big")
        a
    }
    else if (a<b)
    {
        println("b is big")
        b
    }
    else    {
        "both are equal"    }

    print("max value is $max")
}

Output:
b is big max value is 10

Comments