Although Kotlin's Elvis operator has cleaner seman...
# language-proposals
a
Although Kotlin's Elvis operator has cleaner semantics (
if (c) a else b
) than the classic one (
a ? b : c
) it's still a branching (#if-considered-harmful), it's awkward to write and it is hard to use with nesting. Why not to provide a functional programming style operator
eitherOr(c, a, b)
, implemented as a function:
Copy code
fun <T>eitherOr(condition: Boolean, first: T, second: T) : T {
    return if (condition) first else second
}
After all, we already have things like
min(a,b)
, `or(a)`etc.
s
That always evaluates both branches.
c
eitherOr.kt
👍 1
you can
inline
as well.
s
I'd much rather write if/else then eitherOr(cond, { smth }, { smth })
5
👍 3
a
You can, already now 😉
g
of course you can, but if not the only person who works with your code I wouldn’t like to see something like this in my codebase. Readability of if/else is much better, it reads naturally. “if-considered-harmful” itself is very doubtful, but also this function is not different from it at all.
a
one can also write
if (a < b) a else b
but why do we have
min(a,b)
?
g
because
min
has semantics, also reads very well.
min from a and b
eitherOr have too abstract semantics. I have nothing against function that hides
condition: Boolean
argument, it’s very handy for sure, but I don’t see how eitherOr would be better, extracting condition to a function tho makes sense, for example such function as getOrElse/getOrPut etc
1
👍 1
e
One reason we have
min
is because of DRY. If you rewrite
min(a, b)
as
if (a < b) a else b
, then you have to repeat both
a
and
b
twice. Not good. Good developers do not repeat themselves.
👍 2
m
@Andy Victors And a Pedantic note. The Elvis operator is
?:
. What you have referenced is the Ternary operator. They are not the same thing, and Kotlin does not have the Ternary operator. The Elvis operator is only for null checking.
Copy code
if(a == null) b else a
a ?: b
Those are equivalent statements.
a
@Mike Thanks for correcting me. 😉
c
If
if
is considered harmful, hiding it behind one level of indirection is not exactly making it harmless 🙂
💯 3
d
All problems in software can be solved by another layer of indirection. If the problem is 'harmful' then the indirection solves this by create 'indirectly harmful' -- which is obvious better then direct harm.
Adding recursion would render the problem harmless by the fact that the harm is unreachable.