Skip to content

Instantly share code, notes, and snippets.

@trevorhackman
Created July 12, 2021 15:35
Show Gist options
  • Save trevorhackman/a6855da0d1a93fa696b92ca202c3a4ee to your computer and use it in GitHub Desktop.
Save trevorhackman/a6855da0d1a93fa696b92ca202c3a4ee to your computer and use it in GitHub Desktop.
Kotlin Ternary Operator with higher-order overloads for lazy evaluation of arguments
inline infix fun <T> Boolean.T(trueOutput: T) = TernaryPart(this, trueOutput)
inline infix fun <T> TernaryPart<T>.F(falseOutput: T) = if (condition) trueOutput else falseOutput
class TernaryPart<T>(val condition: Boolean, val trueOutput: T)
// T overload for conditional evaluation of functional arguments
infix fun <T> Boolean.T(trueBranch: () -> T) = TernaryPart(this, trueBranch)
// F overload for conditional evaluation of functional arguments
inline infix fun <T, U: () -> T> TernaryPart<U>.F(falseBranch: U) = if (condition) trueOutput() else falseBranch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment