Created
September 20, 2015 10:22
-
-
Save mykola-dev/3276821cef03fd515442 to your computer and use it in GitHub Desktop.
Kotlin Ternary Operator implementations
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
package ds.features.kotlin | |
fun ternaryTest() { | |
val rand = Math.random() | |
val logged = isLoggedIn() | |
// ternary | |
val a = (rand > 0.5)(1, 0) | |
val b = isLoggedIn()["logged", "screwed"] | |
val c = isLoggedIn() then "logged" ?: "screwed" | |
val d = logged { "logged" to "screwed" } | |
val e = (rand < 0.5) % 0 ?: 1 | |
} | |
// ternary A | |
inline fun Boolean.invoke<T>(yes: T, no: T): T = if (this) yes else no | |
// ternary B | |
inline fun Boolean.get<T>(yes: T, no: T): T = if (this) yes else no | |
// ternary C | |
inline fun Boolean.then<T>(param1: T): T? = if (this) param1 else null | |
// ternary D | |
inline fun Boolean.invoke<T>(f: () -> Pair<T, T>): T { | |
val (yes, no) = f() | |
if (this) return yes else return no | |
} | |
// ternary E | |
inline fun Boolean.mod<T>(param: T): T? = if (this) param else null | |
fun isLoggedIn() = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment