Another beginners’ question about `Long` and `Numb...
# javascript
g
Another beginners’ question about
Long
and
Number
. I have this Kotlin code:
Copy code
@JsExport
fun isNegative(amount: Long) : Boolean = amount < 0L
which fails at runtime in Typescript because
Copy code
TypeError: amount.compareTo_n4fqi2_k$ is not a function
Can someone gently guide me towards what kind of solutions I should be investigating? Should I just not use
Long
in the Kotlin code, or should I be adding some conversion logic somewhere?
I know that numbers are floating-point in JS, and I’m okay with that, so I’m looking for the least painful way to consume this existing Kotlin code in a JS environment.
e
you should avoid using Long that interoperates with JS/TS code
b
Long type is not external, annotated with @JsExport nor mapped to js native type by the compiler. As such its usage in other @JsExport declarations is unsafe.
g
OK, thanks. Looks like I have some pain ahead of me.
b
Just using Int should be safe enough in JS
g
Yeah,
Int
isn’t big enough on Android/iOS though. I’d love to find a compromise where I can use a
Long
implementation on platforms which support it, and floating-point on JS. I’ll see if I can get anywhere with `expect`/`actual`
b
Hmm, declare your own MyLong value class with boxed Number value, then override it to Long in your actual implementation on android/ios, and Int on js
Or just have a separate function on js that calls you mpp function and converts the result to int before returning
e
yeah, instead of @JsExport'ing your function, @JsExport a wrapper that converts to Int (or Double for some more range) if you need to use it as a Number in JS
(and if you don't need it as a Number, I'd stringify it but I don't think everybody agrees on that)
g
So this seems to do kinda what I need. common:
Copy code
expect class YNum : Number, Comparable<YNum>
Android/iOS:
Copy code
actual typealias YNum = Long
JS:
Copy code
actual typealias YNum = Double
e
that feels like a bad idea;
x / y * y
will give different results on different platforms
use Int or Long everywhere as appropriate in Kotlin-only code and add JS wrappers as necessasry