Hi guys, this one keeps coming regularly for me ...
# announcements
j
Hi guys, this one keeps coming regularly for me Is there a nice way of dealing with this ? I saw the SO about it but wasn’t great.
Copy code
// The below code results in a compilation error
data class ViewModel(
    var lineSpeed: Int? = null
)

val viewModel = ViewModel()

if(viewModel.lineSpeed != null && viewModel?.lineSpeed > 0 ) {}

//Error : Smart cast to 'Int' is impossible, because 'viewModel.lineSpeed' is a mutable property that could have been changed by this time
l
either set a default value, use a constructor or use
!!
when accessing the (mutable/nullable) variable
or
Copy code
viewModel.lineSpeed?.let{
    if(it>0) ....
}
a
or
Copy code
viewModel.lineSpeed?.takeIf { it > 0 }?.let {

}
👍 2
s
Copy code
fun Int?.isGreaterThan(a: Int) = this != null && this > a

if (viewModel.lineSpeed.isGreaterThan(3)) {

}
😵 1
r
I usually use a local variable
👍 4
j
Thanks for all the replies guys, plenty to choose from