2

I know that implicit conversions are available for js.FunctionN <–> scala.FunctionN. However, if I work with libraries in dynamic fashion (without typed facade), they won't help me, because the compiler obviously doesn't know that I need a conversion. For example, if a JS code expects a JS Array with a string and a function as an input -- something like

['Hello world', function ($x, $y) {
    console.log($x + $y)
}],

, I can't create it in Scala like this:

    val a: js.Array[Any] = js.Array(
      "Hello world",
      (x: Int, y: Int) => {console.log(x + y)}
    )
  )

Because Scala function will not be converted to JS function. Does there exist some explicit conversion method for that, similar to toJSArray for mutable Seq? I've checked that asInstanceOf[js.Function] doesn't work.

1 Answer 1

5

asInstanceOf doesn't work because that is basically saying "this function is already a js.Function", which isn't true. But this does usually convert correctly if you give it an explicit type ascription, like this (haven't tried compiling but should be roughly correct):

val a: js.Array[Any] = js.Array(
  "Hello world",
  { (x: Int, y: Int) => {console.log(x + y)} }:js.Function2[Int, Int, Unit]
)

It's a bit more boilerplate, but that's always the cost of going without facades...

Sign up to request clarification or add additional context in comments.

1 Comment

You can make it less boilerplaty by ascribing as : js.Function rather than the js.Function2[...] verbose thing. But otherwise, yes, that's pretty much what you have to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.