Skip to content

Instantly share code, notes, and snippets.

@dariushm2
Last active May 15, 2023 02:14
Show Gist options
  • Save dariushm2/786233811f2bee29a55d84e10abc20ca to your computer and use it in GitHub Desktop.
Save dariushm2/786233811f2bee29a55d84e10abc20ca to your computer and use it in GitHub Desktop.
Elvis Operator in Kotlin
data class ElvisOperator<T>(
val condition: Boolean?,
val trueValue: T?,
) {
operator fun minus(falseValue: T?): T? =
if (condition == true) trueValue else falseValue
}
operator fun <T> Boolean?.plus(trueValue: T?) =
ElvisBuilder(this, trueValue)
fun example() {
val s = "1"
var a: String? = null
var b: String? = null
(s == "1") + 1 - 2
(s != "1") + 1 - 2
(s == "10") + 10 - null
(s == "1") + a - b
a = "something"
b = "anything"
(s == "1") + a - b
val resutl: String? = (s == "1") + a - b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment