I'm trying to have such a function in Wasm target ...
# webassembly
p
I'm trying to have such a function in Wasm target (it works fine for other targets):
Copy code
internal actual fun isInteger(value: Any): Boolean =
    js("return Number.isInteger(value)")
but I'm getting
Type 'Any' cannot be used as value parameter type of JS interop function. Only external, primitive, string, and function types are supported in Kotlin/Wasm JS interop.
. Tried also with
Number
as the arg type. Is there an idiomatic way of dealing with these? Maybe even the function's body can be implemented in a better way, but first I need to sort out the function's signature being invalid
r
You can only use JsAny.
p
but it's not available in the common source set, in the
expect
function
r
You could create a second, private function with JsAny parameter and call it with some forced, unsafe casting. But it will crash is you pass something other than js object.
p
sorry, I don't quite get how I would get past having a valid arg type in
actual
function for Wasm
r
p
fun isInteger(value: Any)
works fine, what's problematic is
*actual* fun isInteger(value: ???)
wait a minute, there's something wrong on my side, one sec
r
the first function in my example can be your "actual"
it's just a simple function and can have
Any
parameter
the second is JS interop and must have
JsAny
you can call the second by casting
Any
to
JsAny
, but as you can see it doesn't work as you could expect (calling with
5
returns
false
).
also no need for
return
in
js()
p
hmm, right - works in regular JS, doesn't work in JS interop, interesting
tried with:
Copy code
private fun isIntegerPrv(value: JsAny): Boolean = js("Number.isInteger(new Number(value))")
but got
Copy code
Unhandled JavaScript exception: can't convert value to number
r
https://pl.kotl.in/ShjFkqWKH check what is logged to the browser console
💡 1
when you pass
5.toJsNumber()
you get
5
, when you pass
5
you get
WasmStructObject
p
good stuff, thanks! I need to make it work also for other number types, but I'll try to get it from here
r
(at least it doesn't crash anymore - I'm sure something like that crashed not long ago 😉 - but I can be wrong because my example works the same with 1.9 as well 😉)
👍 1
c
You could create a second, private function with JsAny parameter and call it with some forced, unsafe casting.
At this point, that second function could just be
dynamic
Ah no sorry this is #CDFP59223, not #C0B8L3U69 🙏
t
Copy code
@file:JsQualifier("Number")

internal external actual fun isInteger(value: JsAny): Boolean
😉
👀 1
And isInteger from Kotlin Wrappers can be used
p
looks like reflection works pretty well for WASM - I was able to reuse the approach I have for the JVM:
Copy code
fun isInteger(value: Number): Boolean {
    return value is Byte || value is Short || value is Int || value is Long
}
demo
👍 1