Reputation: 306
I'm really new to Kotlin, and what I want is something like:
when_assert_no_else {
CONDITION0 -> {
doSomething0()
}
CONDITION1 -> {
doSomething1()
}
}
which works just like
when {
CONDITION0 -> {
doSomething0()
}
CONDITION1 -> {
doSomething1()
}
else -> {
throw RuntimeException()
}
}
The latter code fragment shows up a lot of time in my project, and I want to assert the control flow is not reaching the else
block by throwing an exception.
Or, is it possible to customize when
keyword by giving an implementation of when_assert_no_else
?
Any idea please? Thank you.
Upvotes: 1
Views: 276
Reputation: 184
I also thought of holi-java's solution but it might not suffice all scenarios. Consider, for example, side-effects in the branches.
What you could do as well is to "abstract" the else branch. What I mean is that you create a (static) class and add a method when_assert_else. In the _when_assert_else_ method you add the code that you which to be executed in the else branch of then when. The advantage over your current strategy is that when you want to change the else branch you'll have to go through all of your code and change it x times. With the function call you would nee to modify it just once.
Upvotes: 0
Reputation: 30676
You can't write the code above since the kotlin don't has ->
operator, but you can make some compromises, for example: using Pair<()->Boolean,()->T>
instead.
fun test(): Int = when_assert_no_else(
{ true } to { 1 },
{ false } to { 2 }
)
fun <T> when_assert_no_else(vararg cases: Pair<() -> Boolean, () -> T>): T {
// v--- short-circuiting terminal operation
return cases.find{ it.first() }
.let { it ?: throw RuntimeException() }
.second()
}
Upvotes: 1