Skip to content

Instantly share code, notes, and snippets.

@Shinpeim
Created October 20, 2017 19:03
Show Gist options
  • Save Shinpeim/3b80a45eeba465b322be5da9503e52bc to your computer and use it in GitHub Desktop.
Save Shinpeim/3b80a45eeba465b322be5da9503e52bc to your computer and use it in GitHub Desktop.

Revisions

  1. Shinpeim created this gist Oct 20, 2017.
    6 changes: 6 additions & 0 deletions 1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,6 @@
    // JS側はこういうインターフェースになってるとする

    exports.nyan = function({a, b}){
    console.log(a);
    console.log(b);
    }
    35 changes: 35 additions & 0 deletions 2.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    import scala.scalajs.js
    import scala.scalajs.js.annotation.{JSExportAll, JSImport}

    // js側が要求する引数の型をtraitで定義して
    @js.native
    trait ArgNative extends js.Object{
    val a: String = js.native
    val b: Int = js.native
    }

    // JSファイルをimport
    @js.native
    @JSImport("./nyan.js", JSImport.Namespace)
    object NyanJS extends js.Object{
    def nyan(args: ArgNative): Unit = js.native
    }

    // js側が要求する型に合わせてScala側から触るcase classを用意して
    @JSExportAll
    case class Arg(a: String, b: Int)


    object Main {
    def main(args: Array[String]): Unit = {
    // scalaからは普通にArgをcaseClassとして使って
    val arg = Arg("hey", 1)

    // こうやってjs側のオブジェクトにキャストして
    val argNative = js.use(arg).as[ArgNative]

    // JSのモジュールに渡す
    NyanJS.nyan(argNative)
    }
    }

    2 changes: 2 additions & 0 deletions 3.result.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    hey
    1