-
-
Save sabiou/0afd30fe45c0baf03bb2793439cf1908 to your computer and use it in GitHub Desktop.
Simplified if-else
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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