Kotlin If Statement

Chapter: Kotlin Last Updated: 17-11-2017 08:02:46 UTC

Program:

            /* ............... START ............... */
                
fun main(args: Array<String>) {

    /*Traditional if else statement in Programming.
    if (testExpression) {
        Run if testExpression is true
    }
    else {
        Run if testExpression is false
    }
    */

    val number = 100

    val result = if (number > 0) {
        "Positive number"
    } else {
        "Negative number"
    }

    println(result)

    val val1 = -8
    val val2 = -20

    val max = if (val1 > val2) {
        println("$val1 is larger than $val2.")
        val1 // Returning value
    } else {
        println("$val1 is larger than $val2.")
        val2
    }
    println("Max Value :  = $max")
}
                /* ............... END ............... */
        

Output

Positive number
-8 is larger than -20.
Max Value :  = -8

Notes:

  • If statement in Kotlin is different from traditional if statment in programming.
  • In Kotlin if expression returns a value and store into a variable.
  • In Kotlin else branch is mandatory when we use if expression. But in java it will allow with only if statment.
  • Please refer to the above program to get more understanding about if statement in Kotlin.
Similar Programs Chapter Last Updated
Kotlin Continue Kotlin 02-03-2018
Kotlin Break Statement Kotlin 27-01-2018
Kotlin For Loop Kotlin 30-11-2017
Kotlin Do While Loop Kotlin 19-11-2017
Kotlin While Loop Kotlin 19-11-2017
Kotlin When Statement Kotlin 18-11-2017
Kotlin Nested If Kotlin 18-11-2017
Kotlin If Else If Statement Kotlin 22-09-2018
Kotlin Print And Println Kotlin 22-09-2018
Kotlin Type Conversion Kotlin 17-11-2017
Kotlin Logical Operators Kotlin 17-11-2017
Kotlin Assignment Operators Kotlin 15-11-2017
Kotlin Arithmetic Operators Kotlin 15-11-2017
Kotlin Data Types Kotlin 12-11-2017
Kotlin Variables Example Kotlin 11-11-2017
Kotlin Comments Example Kotlin 11-11-2017
Kotlin Hello World Kotlin 11-11-2017

1