Scala Scala.js导入JavaScript模块会产生错误'method value is not a member of'



我正在尝试将JavaScript类模块script.js导入scala程序main.scala并使用其方法adddivide

我使用scala.js导入JS脚本和SBT构建。

然而,当我尝试运行程序时,我得到错误:

value add is not a member of example.MyType

value divide is not a member of example.MyType

你能帮我找出问题在哪里吗?

提前感谢!

代码看起来是这样的!

main.scala


package example
import scala.scalajs.js
import scala.scalajs.js.annotation._
@js.native
@JSImport("script.js","MyType")
class MyType(var x:Double, var y:Double) extends js.Object {
add(z: Int) 
divide(z: Int) 
}
object Hello extends App {
work() // Sum: 1, Divide: 6
@JSExport
def work(): Unit = {
val added = new MyType(1,2).add(3)
println(s"Sum: $added,") // 1
val divided = new MyType(4,3).divide(2)
println(s"Divide: $divided") // 6
}
}

script.js:


class MyType {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(z){
let {x,y} = this;
return x + y + z;
}
divide(z){
let {x,y} = this;
return (x + y)/z;
}
};
module.exports = {MyType};

plugins.sbt:


addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

build.sbt:


import Dependencies._
ThisBuild / scalaVersion     := "2.13.8"
ThisBuild / version          := "0.1.0-SNAPSHOT"
ThisBuild / organization     := "com.example"
ThisBuild / organizationName := "example"
lazy val root = (project in file("."))
.settings(
name := "add",
libraryDependencies += scalaTest % Test
)
enablePlugins(ScalaJSPlugin)
scalaJSUseMainModuleInitializer := true
// See https://www.scala-sbt.org/1.x/docs/Using-Sonatype.html for instructions on how to publish to Sonatype.

看起来您对定义方法的Scala语法有点困惑。adddivide应声明为

@js.native
@JSImport("script.js","MyType")
class MyType(var x:Double, var y:Double) extends js.Object {
def add(z: Int): Double = js.native
def divide(z: Int): Double = js.native
}

最新更新