Skip to content

Instantly share code, notes, and snippets.

@ragdroid
Created March 2, 2019 14:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ragdroid/a74bddc13a6e391aa966d7f43be0ea04 to your computer and use it in GitHub Desktop.
Save ragdroid/a74bddc13a6e391aa966d7f43be0ea04 to your computer and use it in GitHub Desktop.
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
Copy link

sabiou commented Mar 5, 2019

Nice one !

@fadi-botros
Copy link

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