Skip to content

Instantly share code, notes, and snippets.

@mykola-dev
Created September 20, 2015 10:05
Show Gist options
  • Save mykola-dev/63ad7f25daf4f25413e5 to your computer and use it in GitHub Desktop.
Save mykola-dev/63ad7f25daf4f25413e5 to your computer and use it in GitHub Desktop.
Kotlin Ternary Operator implementations
package ds.features.kotlin
fun ternaryTest() {
val rand = Math.random()
// ternary
val a = (rand > 0.5)(1, 0)
val b = isLoggedIn()["logged", "screwed"]
val c = isLoggedIn() then "logged" ?: "screwed"
val d = isLoggedIn() { "logged" to "screwed" }
}
// 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
}
fun isLoggedIn() = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment