Scala error when defining class

2019-09-13 17:39发布

问题:

I am following the Scala course from Coursera and I have implemented the follwong class:

 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;
  }

}

However, I get many compilation errors. The first of them appears on the first line:

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

The file containing the code is called

Rational.scala

Why does this error appear?

回答1:

Your main method has to live in the companion 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;
  }
}

I also changed the main method signature, as it prevents errors to specify an explicit return type and to use "=". As a rule of thumb: Never omit the "=" sign.

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

instead of

  def main(args: Array[String]) {


回答2:

I encounter the error message self constructor arguments cannot reference unconstructed this as soon as I define a class inside an eclipse scala-ide worksheet (.sc File), and give the same class name to it (by accident), as I named a class definition outside the worksheet. Removing the duplicate class name let's the error disappear.



标签: scala