Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ScalaJS: How to create Option[A] from JS?

Tags:

scala.js

I have a ScalaJS function that I would like to call from JS, that has an Option[String] parameter. I could not figure out how to create Some[String] and None[String] from JS.

like image 489
Eduardo Avatar asked Feb 09 '23 20:02

Eduardo


1 Answers

Short answer: you can't. There are two solutions to your problem, though.

Exposing global functions to construct Somes and retrieving None (suboptimal)

Add an object like this in your Scala.js codebase:

package some.pack

@JSExport
object OptionFactory {
  @JSExport
  def none(): None.type = None

  @JSExport
  def some[A](value: A): Some[A] = Some(value)
}

You can now use that factory from JS to create options:

var none = some.pack.OptionFactory.none()
var some = some.pack.OptionFactory.some(5)

Directly expose an API manipulating js.UndefOr (recommended)

Instead of forcing JS to manipulate Options, you can expose a JS-friendly API directly from your Scala.js class. Suppose your function that you want to expose is something like:

def foo(opt: Option[Int]): Unit = ???

You can instead, or in addition, export the following JS-friendly version:

@JSExport
def foo(opt: js.UndefOr[Int]): Unit = foo(opt.toOption)

which will allow JS to simply use undefined for None and any integer for Some[Int], e.g.:

scalaJSObj.foo(undefined)
scalaJSObj.foo(5)
like image 170
sjrd Avatar answered Feb 15 '23 17:02

sjrd