Which is better and why? :one: This is broken ```...
# codereview
e
Which is better and why? 1️⃣ This is broken
Copy code
return binding.myField.getWidth() != 0 ? binding.myField.getWidth() : binding.otherField.getWidth()
2️⃣
Copy code
return binding.myField.getWidth().let {
    if (it != 0) it else binding.otherField.getWidth()
}
3️⃣ by @Luke
Copy code
return if (binding.myField.getWidth() != 0) binding.myField.getWidth() else binding.otherField.getWidth()
l
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
Whoops! I need to fix that. 😊
l
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
@Luke Yeah, me too. It's not my code.
k
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