I still find myself doing something like: ``` if ...
# getting-started
c
I still find myself doing something like:
Copy code
if (viewModel.value?.items()?.subItems != null) {
    //Do my thing
}
I don't think this is bad because it's straight forward. As long as that statement is not null I want to execute some code. Is there a more idiomatic way of doing this?
a
Copy code
viewModel.value?.items()?.subItems?.let { //or run, apply, etc..
   //do your thing
}
I personally prefer
with
. Feels quite declarative:
Copy code
with(viewModel.value?.items()?.subItems?) {
    map(propertyA)
    println(size)
    //example
}
a
Is there a way to handle the null case using with? I typically use let because it allows for the elvis operator.
viewmodel?.value?.items()?.subItems?.let { doThing(it) } ?: handleNullSubItems()
k
Use custom extensions
a
oh yeah that makes sense.
k
You could probably do something like this:
private val ViewModel?.subItems: List<SubItemType> get() = value?.items()?.subItems.orEmpty()
and then use a normal if statement (which is more readable imo but it really depends on the situation), also assuming that items being null or empty list is semantically same thing to you
c
All of these feel like more work to understand than just the if statement. 😭 Maybe I just don't understand let, run, apply, with...
k
I prefer the if as well.