Is there any way to convert/cast a function/lambda...
# webassembly
r
Is there any way to convert/cast a function/lambda to
JsAny
? With K/JS we can have a
dynamic
property which accepts any values, including functions (or lambdas). With K/Wasm we should use
JsAny
instead, but I don't see any way to assign a function to
JsAny
property.
s
If possible, use lambda type directly instead of
JsAny
, for example:
Copy code
external fun foo(x: (Int) -> Int)
Or you can convert function to JsAny by round-tripping it thought JS:
Copy code
fun toJsAny(f: (Int) -> Int): JsAny = js("f")
The conversion from Kotlin to JS lambdas is currently implemented only in
external
or
js()
boundary.
r
Is it possible for some general function type? Something like this:
Copy code
fun toJsAny(f: Function<*>): JsAny = js("f")
s
Currently not
😢 1
r
Thanks anyway, I'll try to manage with a bunch of js functions for all my required types.
https://pl.kotl.in/fShSuM3NA I'm playing a bit with the code and it's beyond my imagination what is the nature of that strange thing returned from
toJsAny(f :..) = js("f")
conversion ... 🙂 What happened to my simple kotlin function? 🙂
I've always thought
js()
just inlines some js code, but what it does with simple "f" ?!
s
JS and Wasm functions are different and need some conversion. Kotlin function object
f
is wrapped with a JS lambda when passed to JS. Similar thing happens to other supported types like
Int
and
String
r
I was sure
String
objects are just copied between Wasm and JS memory... But my function is not copied - it is still able to access it's kotlin closure: https://pl.kotl.in/jRPww3xme
s
This is true, JS closure closes over Kotlin object. It also converts paramters and return values between Kotlin and JS when called.