2 ms·
Kotlin will do exhaustive checks in a `when` block when it is an expression. You can add a `.let { }` at the end of the when statement if you want to enforce t
by dangets 7y ago
Kotlin will do exhaustive checks in a `when` block when it is an expression. You can add a `.let { }` at the end of the when statement if you want to enforce this and not really return anything.
sealed class Communication
data class Email(val emailAddress: String) : Communication()
data class Shouting(val preferredName: String) : Communication()
object HiveMind : Communication()
fun exhaustiveWhen(comm: Communication) {
// not exhaustively checked (will compile)
when (comm) {
is Email -> println("sending email to ${comm.emailAddress}")
}
// *is* exhaustively checked (error at compile time)
// must add HiveMind or 'else' branch
val result = when (comm) {
is Email -> println("sending email to ${comm.emailAddress}")
is Shouting -> println("HELLO, ${comm.preferredName}!")
}
// *is* exhaustively checked
when (comm) {
is Email -> println("sending email to ${comm.emailAddress}")
is Shouting -> println("HELLO, ${comm.preferredName}!")
}.let { }
}
- still_grokking 7y agoSure. But that doesn't look helpful to me as it works only sometimes… Even the syntax can be made less awkward[1] this look still like a wonky hack to me where the user can do way to much wrong. [1] https://proandroiddev.com/til-when-is-when-exhaustive-31d69f630a8b https://proandroiddev.com/til-when-is-when-exhaustive-31d69f...