Created
March 2, 2019 14:00
-
-
Save ragdroid/a74bddc13a6e391aa966d7f43be0ea04 to your computer and use it in GitHub Desktop.
Simplified if-else
This file contains hidden or 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 hidden or 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) | |
} |
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
Nice one !