Skip to content

Instantly share code, notes, and snippets.

@dladukedev
Created July 31, 2023 14:53
Show Gist options
  • Save dladukedev/5cc1a5c42ad77b3919814531326b7bb0 to your computer and use it in GitHub Desktop.
Save dladukedev/5cc1a5c42ad77b3919814531326b7bb0 to your computer and use it in GitHub Desktop.
Exhaustive when blocks in Kotlin
import kotlin.random.Random
val myInt = Random.nextInt()
val myBool = Random.nextBoolean()
// Expression - Exhaustive Required
val result = when(myInt) {
1 -> "I'm #1!"
else -> "I'm something else"
}
// Statement - Exhaustive Not Required
when(myInt) {
1 -> { print("I'm #1!")}
}
// Subject is Restrictive Type - Exhausted Required
when(myBool) {
true -> { print("This Statement is True")}
false -> { print("This Statement is False")}
}
// Subject is Not Restrictive Type - Exhaustive Not required
when(myInt) {
1 -> { print("I'm #1!")}
}
// else Ensures when is Exhaustive
when(myInt) {
else -> { print("I'm an Integer") }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment