is it impossible to use -- and ++ operators with a...
# getting-started
j
is it impossible to use -- and ++ operators with a nullable Int ?
this is a little clunky
Copy code
val sr: Int
            if (bd.stepsRemaining == null) {
                sr = Int.MAX_VALUE
            } else {
                sr = bd.stepsRemaining!!
                bd.stepsRemaining = (bd.stepsRemaining!!) - 1
            }
e
Copy code
val sr = bd.stepsRemaining
    ?.also { bd.stepsRemaining = it - 1 }
    ?: Int.MAX_VALUE
(can be simplified if you don't need
sr
)
r
Also
Copy code
operator fun Int?.dec(): Int? = this?.dec()
...
val sr = bd.stepsRemaining-- ?: Int.MAX_VALUE
j
thanks!
a
a clean approach :
Copy code
val sr:Int=when(bd.stepsRemaining){
    null -> Int.MAX_VALUE
    else -> bd.stepsRemaining-- 
}
j
Hmm:
(adding the !! does not make it happy either)
e
yeah that'll only work when it can smart cast, which has limitations like local final class in local val with non-computed property
if it can't be smart cast, it needs to be stored in a local val, e.g.
Copy code
val sr = when (val sr = bd.stepsRemaining) {
    null -> Int.MAX_VALUE
    else -> sr.also { bd.stepsRemaining = it - 1 }
}
but that's just more complex than the previous solutions
1