Last active
May 15, 2023 02:14
-
-
Save dariushm2/786233811f2bee29a55d84e10abc20ca to your computer and use it in GitHub Desktop.
Elvis Operator in Kotlin
This file contains 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
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