Skip to content

Instantly share code, notes, and snippets.

@sabiou
Forked from ragdroid/IfElse.kt
Created March 5, 2019 02:58
Show Gist options
  • Save sabiou/0afd30fe45c0baf03bb2793439cf1908 to your computer and use it in GitHub Desktop.
Save sabiou/0afd30fe45c0baf03bb2793439cf1908 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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment