any other alternative to suggest on below snippet ...
# codingconventions
m
any other alternative to suggest on below snippet code? 1️⃣
Copy code
fun doSomething(): String {
  return if 
    aMethodHere1()
  else
    aMethodHere2()
}
2️⃣
Copy code
fun doSomething(): String {
  return if aMethodHere1()
  else aMethodHere2()
}
3️⃣
Copy code
fun doSomething(): String {
  return if aMethodHere1() else aMethodHere2()
}
3️⃣ 1
1️⃣ 1
m
That’s not valid Kotlin code, is it?
t
I might overlook something, but looks valid to me. and I prefer 3, in my brain it is the safest choice to avoid
{}
and still avoid gotofail
✍️ 1
m
ooops apologize 🙏 I’ve updated the snippet
h
it still won't compile, the
if
hasn't any condition
🙏 1
☝️ 1
😅 1
m
My preference for these short functions is to use
when
and to go without method body. The arrows make it very obvious what’s happening, as opposed to the if condition parentheses.
Copy code
fun isSpecial(x: Int) = when {
    x == 42 -> "very"
    else -> "dunno"
}
g
Neither for me, 1️⃣ and 2️⃣ are against of the style guide, and I really don’t like how it looks. Use 3️⃣ but for very short cases and mostly for expression body functions For this particular case I would probably use something like:
Copy code
fun doSomething(): String = if (...) {
  aMethodHere1()
} else {
  aMethodHere2()
}
when
as suggested by Michael also an option, but I usually avoid when which has only one condition, it looks more natural for me to use if/else for such case PS It would be better to fix snipper and use valid Kotlin code, if you add correct condition to
if
this code will look quite differently in terms of style
🙏 1
👌 1