Created
July 31, 2023 14:53
-
-
Save dladukedev/5cc1a5c42ad77b3919814531326b7bb0 to your computer and use it in GitHub Desktop.
Exhaustive when blocks in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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