Scala 公共方法:';'预期但“def”成立

发布于 2024-11-13 06:32:45 字数 415 浏览 9 评论 0原文

我写了这个方法:

public def getXScaleFactor(panelWidth: Int): Double = {
  return (panelWidth / (samplesContainer[0].length.asInstanceOf[Double]))
}

并且我在编译时遇到问题:

[error] ./src/main/scala/Controllers/TrackController.scala:85: ';' expected but 'def' found.
[error]   public def getXScaleFactor(panelWidth: Int): Double {
[error]          ^

这段代码有什么问题?

I wrote this method:

public def getXScaleFactor(panelWidth: Int): Double = {
  return (panelWidth / (samplesContainer[0].length.asInstanceOf[Double]))
}

and I have problems with compilation:

[error] ./src/main/scala/Controllers/TrackController.scala:85: ';' expected but 'def' found.
[error]   public def getXScaleFactor(panelWidth: Int): Double {
[error]          ^

What is wrong in this code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我家小可爱 2024-11-20 06:32:45

public 不是 Scala 中的保留字,因此它将其解释为变量名。默认为公共访问;只要去掉 public 就可以了。

public is not a reserved word in Scala, so it's interpreting it as a variable name. Public access is the default; just leave off public and you'll be fine.

还不是爱你 2024-11-20 06:32:45

方法默认是公共的。删除public

Methods are public by default. Remove public.

我乃一代侩神 2024-11-20 06:32:45

只是为了添加上面的答案:

您还可以删除 return 关键字。函数/方法中的最后一个语句/表达式自动成为返回值。

Just to add up to the answers above:

You can also remove return keyword. The last statement/expression in a function/method is automatically the return value.

再见回来 2024-11-20 06:32:45

问题在于您已经编写了 Java 代码。

除了 public 之外,您还使用 [] 对集合进行索引访问(这是无效的)、显式返回类型(这不是必需的), return (这也是不需要的)和 .asInstanceOf (这是不必要的,并且有代码味道)

尝试这个以获得轻量级、更惯用的体验:

def xScaleFactor(panelWidth: Int) =
  panelWidth / samplesContainer.head.length.toDouble

或者如果 < code>samplesContainer 可能为空:

def xScaleFactor(panelWidth: Int) =
  panelWidth / samplesContainer.headOption.map(_.length.toDouble).getOrElse(42.0)

放入任何内容更喜欢代替默认的 42

The problem is that you've written Java code.

As well as public, you've also used [] for indexed access to a collection (which is invalid), an explicit return type (which isn't needed), return (which also isn't needed), and .asInstanceOf (which is unnecessary, and a code smell)

Try this for a lightweight, more idiomatic experience:

def xScaleFactor(panelWidth: Int) =
  panelWidth / samplesContainer.head.length.toDouble

Or if samplesContainer might be empty:

def xScaleFactor(panelWidth: Int) =
  panelWidth / samplesContainer.headOption.map(_.length.toDouble).getOrElse(42.0)

Put whatever you prefer in place of the default 42 there

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文