https://kotlinlang.org logo
Title
b

Ben

04/08/2020, 10:54 AM
I have some code that in Java I'd write
if (getFoo() != null && barEnabled()) {
    doSomething();
}
In Kotlin I could write
getFoo().takeIf { barEnabled() }?.let { doSomething() }
but I'm not convinced that's any easier to read, mostly because of the separation between the nullable getFoo() and the let. Any recommendations on how best to write that in Kotlin? Is using scope functions always preferred?
d

diesieben07

04/08/2020, 11:07 AM
imho there is absolutely nothing wrong with an if statement here. It perfectly captures your intent.
j

Johannes Zick

04/08/2020, 11:08 AM
It's possible to use scope functions, but not always recommended. I used to overuse them as well. Use them if you actually want to chain something on the value, not to replace if checks.
b

Ben

04/08/2020, 11:21 AM
Thanks both, that makes sense! 👍