What’s the correct way to transform a `NSNumber` t...
# kotlin-native
k
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
Unfortunately I’m dealing with both
NumberFormatter
and
NSNumberFormatter
which exclusively parse to their respective platform number types
r
You can probably make extensions to map
NSNumber
to kotlin types, but they aren’t all subtypes of
Number
k
I ended up going with
Copy code
checkNotNull((number as? Double) ?: (number as? Long)) {
            "$number is not either a Double or a Long."
        }
r
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
Good call
j
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.
157 Views