https://kotlinlang.org logo
#kotlin-native
Title
# kotlin-native
k

kevin.cianfarini

07/06/2022, 2:01 PM
What’s the correct way to transform a
NSNumber
to
kotlin.Number
? Is it just
myNsNumber as Number
?
NSNumber
can be a
Boolean
while Kotlin
Number
cannot, so
NSNumber
and Kotlin’s
Number
can’t match.
You should probably not use NSNumber, the same way you should probably not use Number in Kotlin
k

kevin.cianfarini

07/06/2022, 2:16 PM
Unfortunately I’m dealing with both
NumberFormatter
and
NSNumberFormatter
which exclusively parse to their respective platform number types
r

ribesg

07/06/2022, 2:18 PM
You can probably make extensions to map
NSNumber
to kotlin types, but they aren’t all subtypes of
Number
k

kevin.cianfarini

07/06/2022, 2:19 PM
I ended up going with
Copy code
checkNotNull((number as? Double) ?: (number as? Long)) {
            "$number is not either a Double or a Long."
        }
r

ribesg

07/06/2022, 2:19 PM
Wouldn’t the first cast always work if it’s not a Boolean?
I would probably use
NSDecimalIsNotANumber
to fail on Booleans and
objCType
to map to the correct Kotlin Number subclass in an extensions
k

kevin.cianfarini

07/06/2022, 2:59 PM
Good call
j

Jeff Lockhart

07/06/2022, 4:39 PM
As long as you know your
NSNumber
is not a boolean,
nsNumber as Number
works, as does
kotlinNumber as NSNumber
. Boolean `NSNumber`s will be 0 or 1 though. I've had to handle
NSNumber
boolean values in dictionaries/maps in another explicit format though.
112 Views