I made a thing that, quite honestly, will make Rom...
# random
y
I made a thing that, quite honestly, will make Roman Elizarov smite me...
Copy code
fun main() {
    println((2 + 2 == 4) `?` {42} `:` {5})
}

@JvmName("questionMark")
infix fun <T> Boolean.`?`(block: () -> T): IfResult<T> = IfResult<T>(if(this) block() else ElseIndicator)

@Suppress("INVALID_CHARACTERS")
@JvmName("colon")
infix fun <T> IfResult<T>.`:`(block: () -> T): T = if(isElse) block() else result as T

object ElseIndicator
@JvmInline value class IfResult<T> internal constructor(internal val result: Any?) {
    val isElse get() = result == ElseIndicator
}
(psssst, it works for bitwise operators too...)
🤣 6
😍 4
K 1
K 1
I think I saw someone do this for bitwise operators a long long time ago, but I can't find that link anymore
I had to use this because I wanted to implement custom comparison operators as part of a DSL where the comparisons shouldn't actually return a boolean i.e.
first < other
should return a custom object and not a boolean
l
y
Lol that was my first thought but I noticed the argument being computed always and the fact that you might wanna produce a null so I ditched it lol. I wonder why all the pro-ternary people haven't just done this 🤷‍♂️
@langara I had a look through your "experiment" and I'm kinda lost for words, wow! It looks very impressive and functional honestly, I just don't think I have the brains to digest it lol. This reminds me of when I, funnily enough, tried to re-implement If-Else expressions, which spiraled me into creating a whole ticket about how lambdas really need more optimizations to allow for structs (did I mention that I spiraled 😁 ) KT-44530 if you're curious
👍 2
m
(psssst, it works for bitwise operators too...)
Yes but no. Part of the push for bitwise operators means actually following the order of operations for operators (removing the excessive need for parenthesis in some circumstances). This would be equivalent to using the existing and/or infix functions.
today i learned 1
r
Reminds me of playing with reimplementing if / else & other boolean operators in Scala a long time ago: https://gist.github.com/Mahoney/3778716