Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simplified if-else
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
}
class IfElseTest {
@Test
fun testIf() {
val condition = true
val output = condition then { 1 + 1 }
assertEquals(2, output)
}
@Test
fun testIfElze() {
val condition = true
val output = condition then { 1 + 1 } elze { 2 + 2 }
assertEquals(output, 2)
}
@Test
fun testIfElzeInt() {
val condition = false
val output = condition then { 1 + 1 } elze { 2 + 2 }
assertEquals(output, 4)
}
@Test
fun testIfElzeString() {
val condition = true
val output = condition then { "Condition is true" } elze { "Condition is false" }
assertEquals(output, "Condition is true")
}
@Test
fun testIfElzeStringFalse() {
val condition = false
val output = condition then { "Condition is true" } elze { "Condition is false" }
assertEquals(output, "Condition is false")
}
@Test
fun testIfElzeObject() {
val condition = true
val output = condition then { TestIfElze(10) } elze { TestIfElze(100) }
assertEquals(output.integer, 10)
}
@Test
fun testIfElzeObjectFalse() {
val condition = false
val output = condition then { TestIfElze(10) } elze { TestIfElze(100) }
assertEquals(output.integer, 100)
}
class TestIfElze(val integer: Int)
}
@sabiou

This comment has been minimized.

Copy link

sabiou commented Mar 5, 2019

Nice one !

@fadi-botros

This comment has been minimized.

Copy link

fadi-botros commented Mar 6, 2019

https://gist.github.com/ragdroid/a74bddc13a6e391aa966d7f43be0ea04#file-ifelse-kt-L2

I think if you added the inline keyword, it would give you more options, like you wouldn't be afraid of extra allocations, so no leaks could happen, also the user of your code could return (in some cases) or do somethings like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.