https://kotlinlang.org logo
Title
e

Ellen Spertus

05/16/2022, 8:01 PM
Which is better and why? 1️⃣ This is broken
return binding.myField.getWidth() != 0 ? binding.myField.getWidth() : binding.otherField.getWidth()
2️⃣
return binding.myField.getWidth().let {
    if (it != 0) it else binding.otherField.getWidth()
}
3️⃣ by @Luke
return if (binding.myField.getWidth() != 0) binding.myField.getWidth() else binding.otherField.getWidth()
l

Luke

05/16/2022, 8:34 PM
2️⃣ because 1️⃣ does not compile. There is no ternary operator in Kotlin. I would go with 3️⃣ :
return if (binding.myField.getWidth() != 0) binding.myField.getWidth() else binding.otherField.getWidth()
e

Ellen Spertus

05/16/2022, 8:35 PM
Whoops! I need to fix that. 😊
l

Luke

05/16/2022, 8:36 PM
Another option is
return binding.myField.getWidth().takeUnless { it == 0 } ?: binding.otherField.getWidth()
👍 1
But I think the basic
if
is the most readable option
🙏 1
👍 1
Maybe a personal preference, but I also prefer the positive conditions in ifs. In this case
binding.myField.getWidth() == 0
vs
binding.myField.getWidth() != 0
👍 1
e

Ellen Spertus

05/17/2022, 1:47 AM
@Luke Yeah, me too. It's not my code.
k

Klitos Kyriacou

05/17/2022, 9:07 AM
Option 3 may fail if another thread changes
myField
width between checking for 0 and returning it. This means it can return 0, something that this
if
statement is trying to prevent.
✔️ 1