【问题标题】:Scala error when defining class定义类时的Scala错误
【发布时间】:2016-12-05 23:15:02
【问题描述】:

我正在学习 Coursera 的 Scala 课程,并且我已经实现了 follwong 类:

 class Rational(x: Int, y: Int) {

  def numer = x;
  def denom = y;

  def add(that: Rational) = 
    new Rational(
        numer * that.denom + that.numer * denom,
        denom * that.denom)

  override def toString = numer + "/" + denom;

  def main(args: Array[String]){
    val x = new Rational(1, 2);
    x.numer;
    x.denom;
  }

}

但是,我收到很多编译错误。 其中第一个出现在第一行:

Multiple markers at this line:

self constructor arguments cannot reference unconstructed this
constructor Rational#97120 is defined twice conflicting symbols both originated in file '/Users/octavian/workspace/lecture2/src/ex3.sc'
x is already defined as value x#97118
y is already defined as value y#97119

包含代码的文件被调用

Rational.scala

为什么会出现这个错误?

【问题讨论】:

  • 主要方法需要在伴生对象中才能工作。另外,你在使用工作表吗?将代码粘贴到 REPL 时可以正常工作

标签: scala


【解决方案1】:

您的 main 方法必须存在于伴侣 object

class Rational(x: Int, y: Int) {

  def numer = x;
  def denom = y;

  def add(that: Rational) =
    new Rational(
      numer * that.denom + that.numer * denom,
      denom * that.denom)

  override def toString = numer + "/" + denom;
}

object Rational {
  def main(args: Array[String]) : Unit = {
    val x = new Rational(1, 2);
    x.numer;
    x.denom;
  }
}

我还更改了主方法签名,因为它可以防止错误指定显式返回类型并使用“=”。根据经验:永远不要省略“=”符号

  def main(args: Array[String]) : Unit = {

而不是

  def main(args: Array[String]) {

【讨论】:

  • 你也可以省略所有的 ;,它们在 scala 代码中基本上不需要/不需要。
  • 为什么要把main方法放在类外?
【解决方案2】:

当我在 eclipse scala-ide 工作表(.sc 文件)中定义一个类时,我遇到错误消息 self constructor arguments cannot reference unconstructed this,并为它(偶然)赋予相同的类名,因为我命名了一个类定义在工作表之外。删除重复的类名让错误消失。

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2011-05-25
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多