Kotlin : When if-else is too mainstream

Source
@Test
fun testIfElze() {
val condition = true
val
output = condition then { 1 + 1 } elze { 2 + 2 }
assertEquals(output, 2)
}

How? Iteration 1

Things are simple when we only wanted to execute the first block if the condition is true and execute elze block if the condition is false. We just needed to create the following two extension functions :

infix fun Boolean.then(action : () -> Unit): Boolean {
if (this)
action.invoke()
return this
}

infix fun Boolean.elze(action: () -> Unit) {
if (!this)
action.invoke()
}
val condition = true
condition then { print("Some Message") } elze { print("Some other message") }

How? Iteration 2

Now we want to capture the value that is returned by our if and elze blocks. To do this and still be able to get the syntactic sugar of calling elze on the block, we need to somehow return the value from the block and also pass on the condition Boolean. i.e. we need to return two things from the first block. To do this we can take advantage of optionals because optionals can hold two things, i.e the value itself and nullability. Let’s modify our extension functions.

infix fun <T>Boolean.then(action : () -> T): T? {
return if (this)
action.invoke()
else null
}

infix fun <T>T?.elze(action: () -> T): T {
return if (this == null)
action.invoke()
else this
}

Caution!

The above code might not be production ready as it could easily get out of hand if we try to access a global variable from within the blocks. We have a chance of leaking the container class. So use with care for simple operations only.

--

--

Android @GoDaddy Studio

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store