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
Lucas Ł
07/19/2018, 2:08 PM
either set a default value, use a constructor or use
!!
when accessing the (mutable/nullable) variable
Lucas Ł
07/19/2018, 2:10 PM
or
Copy code
viewModel.lineSpeed?.let{
if(it>0) ....
}
a
arekolek
07/19/2018, 2:10 PM
or
Copy code
viewModel.lineSpeed?.takeIf { it > 0 }?.let {
}
👍 2
s
Sam Woodall
07/19/2018, 2:12 PM
Copy code
fun Int?.isGreaterThan(a: Int) = this != null && this > a
if (viewModel.lineSpeed.isGreaterThan(3)) {
}
😵 1
r
robstoll
07/19/2018, 2:28 PM
I usually use a local variable
👍 4
j
Jiddles
07/19/2018, 3:27 PM
Thanks for all the replies guys, plenty to choose from