Kotlin Training Program

DOWNLOAD APP

FEEDBACK

if-else-if & when statement

To check multiple condition, we can use if-else-if chains :

 if (/* Condition 1 */) {
    // Code
} else if (/* Condition 2 */) {
    // Code
} else if (/* Condition 3 */) {
    // Code
} else {
    // Code
}
 

We can chain as many if-else blocks as we need. Note that only one of these blocks will get executed based on the first condition that is met. If multiple conditions are met, the block under first condition gets executed.

To make the if-else-if chains code much more concise, we can use the when statement :

 when {
    /* Condition 1 */ -> {
        // Code
    }
    /* Condition 2 */ -> {
        // Code
    }
    else -> {
        // Code
    }
}
 

Similar to if-else-if chains, only one of the branches under when will be executed. else branch gets executed when none of the consition is met & it is optional.

when statement can also be used for comparing value of an expression :

 when (/* Expression */) {
    /* Possible value 1 */ -> {
        // Code
    }
    /* Possible value 2 */ -> {
        // Code
    }
    else -> {
        // Code
    }
}
 

For example, suppose we have a variable named rank which denotes the rank secured by a person in a competition. Based on the rank, we want to set rankLabel as (1 -> Winner, 2 -> First Runner Up, 3 -> Second Runner Up, else -> Participant). So, we can use when statement like this :

 fun main() {
		print("Enter your rank: ")
		val rank = readln().toInt()
	
		var rankLabel: String
		when (rank) {
		    1 -> {
		        rankLabel = "Winner"
		    }
		    2 -> {
		        rankLabel = "First Runner Up"
		    }
		    3 -> {
		        rankLabel = "Second Runner Up"
		    }
		    else -> {
		        rankLabel = "Participant"
		    }
		}
		
		println("Your rank is $rankLabel")
}
 

Statement as Expression

All if-else, if-else-if & when statements are expressions in Kotlin i.e. based on the condtion met, they represent a value. We can then store this value in variable. In the above rank example, we can make the code more concise like this :

 var rankLabel = when (rank) {
    1 -> "Winner"
    2 -> "First Runner Up"
    3 -> "Second Runner Up"
    else -> "Participant"
}
 

Similarly, if-else & if-else-if statements are also expressions. We can re-write the above code using if-else-if :

 var rankLabel = if (rank == 1) {
    "Winner"
} else if (rank == 2) {
    "First Runner Up"
} else if (rank == 3) {
    "Second Runner Up"
} else {
    "Participant"
}