https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jonathan Ellis

06/08/2022, 7:54 PM
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

ephemient

06/08/2022, 8:01 PM
Copy code
val sr = bd.stepsRemaining
    ?.also { bd.stepsRemaining = it - 1 }
    ?: Int.MAX_VALUE
(can be simplified if you don't need
sr
)
r

Ruckus

06/08/2022, 8:04 PM
Also
Copy code
operator fun Int?.dec(): Int? = this?.dec()
...
val sr = bd.stepsRemaining-- ?: Int.MAX_VALUE
j

Jonathan Ellis

06/08/2022, 8:21 PM
thanks!
a

Anouar di Kali

06/08/2022, 11:50 PM
a clean approach :
Copy code
val sr:Int=when(bd.stepsRemaining){
    null -> Int.MAX_VALUE
    else -> bd.stepsRemaining-- 
}
j

Jonathan Ellis

06/09/2022, 3:00 AM
Hmm:
(adding the !! does not make it happy either)
e

ephemient

06/09/2022, 3:28 AM
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
2 Views