Scala class definition error

I follow the Scala course from Coursera, and I implemented the following 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 a lot of compilation errors. The first one appears in 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?

0
source share
2 answers

Your method mainshould live in a companionobject

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 signature of the method, since it does not allow errors to indicate an explicit return type and use "=". Typically: Never lower the "=" sign .

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

instead

  def main(args: Array[String]) {
+1
source

self constructor arguments cannot reference unconstructed this, eclipse scala -ide (.sc File), (), . .

0

Source: https://habr.com/ru/post/1608369/


All Articles