Skip to content

Instantly share code, notes, and snippets.

@mykola-dev
Created September 20, 2015 09:54
Show Gist options
  • Save mykola-dev/6a19910f07d22666e696 to your computer and use it in GitHub Desktop.
Save mykola-dev/6a19910f07d22666e696 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"
}
// 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
fun isLoggedIn() = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment