Left Index

Kotlin If Expression

In this article, you will learn to use if expression in Kotlin with the help of examples. Let's see syntax of if expression:

Syntax:
// conditional expression which return true or false
if(condition) {
	// TODO your task
} else {
	// TODO otherwise task
}

If executes a certain section of code if the condition is evaluated to true. It can have optional else clause. Codes inside else clause are executed if the condition is false.


There is various type of if expression in Kotlin:

  • if-else expression
  • if-else if expression
  • nested if expression

If-else expression example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var num1 = 10
	
	// you can try if-else like
	var num2 = if(num1 == 10) {
		20
	} else {
		30
	}
	println("Value of num2: ${num2}")
		
	// tradition way to use if-else
	if(num1 == 11) {
		println("Value of num1: ${num1}")
	} else {
		println("Value of num1: ${num1}")
	}
	
	// other way of using if-else like ternary operator in ternary operator
	var num3 = if(num1 == 10) 35 else 25
	println("Value of num3: ${num3}")
}
Output:
Value of num2: 20
Value of num1: 10
Value of num3: 35

if-else-if expression example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var num1 = 10
	
	// you can try if-else like
	var num2 = if(num1 == 10) {
		20
	} else if(num1 == 11) {
		30
	} else {
		5
	}
	
	println("Value of num2: ${num2}")
	
	
	// tradition way to use if-else
	if(num1 == 11) {
		println("Value of num1: ${num1}")
	} else if(num1 == 10) {
		println("Value of num1: ${num1}")
	} else {
		println("Value of num1: ${num1}")
	}
	
	
	// other way of using if-else like ternary operator in ternary operator
	var num3 = if(num1 == 10) 35 else if(num1 == 11) 25 else 15
	println("Value of num3: ${num3}")
}
Output:
Value of num2: 20
Value of num1: 10
Value of num3: 35

nested if-else example:
package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var num1 = 10

	// you can try if-else like
	var num2 = if (num1 == 10) {
		20
	} else {
		if (num1 == 11) {
			30
		} else {
			5
		}
	}

	println("Value of num2: ${num2}")


	// tradition way to use if-else
	if (num1 == 11) {
		println("Value of num1: ${num1}")
	} else {
		if (num1 == 10) {
			println("Value of num1: ${num1}")
		} else {
			println("Value of num1: ${num1}")
		}
	}
}
Output:
Value of num2: 20
Value of num1: 10