Scala: Access to parameters of class parameters and access to objects

I come from the Java background and are new to Scala, currently looking at the book "Scala Programming."

The book gives an example:

class Rational(n: Int, d: Int) { // This won't compile
  require(d != 0)
  override def toString = n + "/" + d

  def add(that: Rational): Rational = new Rational(n * that.d + that.n * d, d * that.d)
}

However, given this code, the compiler complains:

error: value d is not a member of Rational
       new Rational(n * that.d + that.n * d, d * that.d)
                             ^
error: value n is not a member of Rational
       new Rational(n * that.d + that.n * d, d * that.d)
                                      ^
error: value d is not a member of Rational
       new Rational(n * that.d + that.n * d, d * that.d)
                                                      ^

The explanation reads:

Although class parameters n and d are in scope in the code of your add method, you can only access their value for the object on which add was called. That way, when you add an implementation of n or d, the compiler will gladly provide you with values ​​for these class parameters. But it will not let you say that.n or that.d, because it does not apply to the Rational object to which add was added. To access the numerator and denominator, you need to enter them in the fields.

:

class Rational(n: Int, d: Int) {
  require(d != 0)
  val numer: Int = n
  val denom: Int = d

  override def toString = numer + "/" + denom

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

, .

n d . add. Rational add. n d, ?

that.n that.d? ?

, toString n d, ?

, , .

+4
2

, , , ( toString), ( that.d ).

, .

class Rational(val n: Int, val d: Int) { // now it compiles
  ...

case class .

case class Rational(n: Int, d: Int) { // this also compiles
  ...
+5

Scala , Java. Scala private[this], " ", , private, " ".

class Rational(n: Int, d: Int)

class Rational(private[this] val n: Int, private[this] val d: Int)

, ,

class Rational(n: Int, d: Int) { ... }

, Rational, n d, , , . val var, Rational, : ( , ) .

+2

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


All Articles