Kotlin Exhaustive if
A previous article covered the scenarios where Kotlin requires a when
block to be exhaustive. As a reminder, a block is "exhaustive" if there is a branch for all possible scenarios. This article is a follow up to that article, this time with a focus on if
blocks.
Unlike a when
block which must be exhaustive in several scenarios, an if
block only needs to be exhaustive when it is used as an expression.
val myInt = Random.nextInt()
// Expression - Exhaustive Required
val result = if (myInt == 1) {
"I'm #1"
} else {
"I'm something else"
}
This is because if
blocks are less "intelligent" in attempting to determine if they are exhaustive since the content of the boolean expression is arbitrary. Due to this, an if
block is only considered exhaustive if it contains a main block and an else block (e.g. if(...) {...} else {...}
). It may additionally include any number of intermediate blocks (e.g. else if(...) {...}
) but they are not required and do not affect whether the block is considered exhaustive or not.
val myBool = Random.nextBoolean()
// Exhaustive not Assumed
val result = if (myBool == true) {
"This is true"
} else if (myBool == false) {
"This is false"
} else {
// Required even if not possible
"Invalid case"
}
When an if
block is used as a statement, it is not required to be exhaustive
val myInt = Random.nextInt()
// Statement - Exhaustive Not Required
if (myInt == 1) {
print("I'm #1!")
}
The if
statement trades correctness for flexibility. It can be used in many situations due to its ability to handle generic boolean expressions but it doesn't have the "intelligence" of the when
block in determining if it includes all possible branches at compile time. The code above is available in this gist for further exploration. Until next time, thanks!
Did you find this content helpful?
Please share this post and be sure to subscribe to the RSS feed to be notified of all future articles!
Want to go above and beyond? Help me out by sending me $1 on Ko-fi. It goes a long way in helping run this site and keeping it advertisement free. Thank you in advance!