https://kotlinlang.org logo
Title
g

gabrielfv

10/11/2017, 7:33 PM
How would you guys recomend to use elvis operator on long expressions with line breaks?
val a = foo.computeBar(Baz::class.java).fetchFirst() ?:
        return@thisComputationFun
or
val a = foo.computeBar(Baz::class.java).fetchFirst()
        ?: return@thisComputationFun
or none at all? The IDE has recomended me to do this in place of the classic
if (a == null) return@thisComputationFun
d

diesieben07

10/11/2017, 7:38 PM
My intuition says
val a = foo.computeBar(Baz::class.java)
           .fetchFirst() ?: return@thisComputationFun
g

gabrielfv

10/11/2017, 7:42 PM
With the return in the same identation?
d

deviant

10/11/2017, 7:42 PM
val a = foo
    .computeBar(Baz::class.java)
    .fetchFirst()
    ?: return@thisComputationFun
d

diesieben07

10/11/2017, 8:03 PM
That looks very weird to me, but I guess it could work
g

gabrielfv

10/11/2017, 8:06 PM
If I had to choose, would be a mix of both:
val a = foo.computeBar(Baz::class.java)
        .fetchFirst() ?:
        return@thisComputationFun
d

diesieben07

10/11/2017, 8:12 PM
I have to disagree with that, if you're just scanning it's easy to miss and you see "oh this just returns" instead "this returns on a condition"
g

gabrielfv

10/11/2017, 8:24 PM
Well, indeed
but on a similar identation to the
val a
it looks like its just returns as well. On a similar level of a
.method()
it draws some more attention.
Another alternative identation might work as well, but I really can't figure a better one
b

bdawg.io

10/12/2017, 6:15 PM
I hate deep nesting (it’s high churn in your code just waiting to happen). I also dislike mixing the location of signal symbols (
.
to invoke a method and
?:
to signal an elvis operation). My vote would be
1. val a = foo.computeBar(Baz::class.java).fetchFirst()
2.     ?: return@thisComputationFun
or
1. val a = foo
2.     .computeBar(Baz::class.java)
3.     .fetchFirst()
4.     ?: return@thisComputationFun
(although I agree with intellij about breaking out this logic from your assignment operator)
2️⃣ 1