https://kotlinlang.org logo
p

Paul Woitaschek

03/04/2021, 1:33 PM
I ran into real weirdnesses with an combined apple source set for watchos and ios because the NSInteger is a long on ios and an int on watchos. This made me write really strange code like this:
Copy code
internal fun NSInteger.toInt(): Int {
  return asInt()
}

private fun Any.asInt(): Int {
  return when (this) {
    is Long -> this.toInt()
    is Int -> this
    else -> error("Could not convert $this to Int")
  }
}
Is there a better way to do that? I’m kind of looking for the opposite of cinterop.convert.
m

mbonnin

03/04/2021, 2:28 PM
I starred that some time ago that looks like it's what you're looking for ? https://youtrack.jetbrains.com/issue/KT-41509
(unfortunately there doesn't seem to be a definitive answer yet)
r

russhwolf

03/04/2021, 2:37 PM
I think
convert()
would still work in this case. But I might be missing something. There are edge cases where it's not what you want.
p

Paul Woitaschek

03/04/2021, 3:21 PM
That issue is definately describing my problem. Convert doesnt help as it's only defined on the kotlin types
r

russhwolf

03/04/2021, 3:33 PM
Ah yeah I see. One workaround then is to leave your public Kotlin APIs in terms of
NSInteger
so you can do whatever conversion you need (
convert()
, or some `expect`/`actual` that differs between 32-bit and 64-big sources) on the Kotlin side.
3 Views