Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help for explain scala problem

Tags:

scala

I have two scala classes (and their Java code when I use javap -private to read the class file).

When I use n and d in the toString method, it will generate private member field in class. Why is that? I'm a little confused.

Scala #1:

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

}

equivalent from javap:

public class com.zjffdu.tutorial.scala.Rational
extends java.lang.Object
implements scala.ScalaObject{
    public com.zjffdu.tutorial.scala.Rational(int, int);
}

Scala #2:

class Rational(n: Int, d: Int) {
  override def toString() = n + "/" + d
}

equivalent from javap:

public class com.zjffdu.tutorial.scala.Rational
extends java.lang.Object
implements scala.ScalaObject{
    private final int n;
    private final int d;
    public java.lang.String toString();
    public com.zjffdu.tutorial.scala.Rational(int, int);
}
like image 926
zjffdu Avatar asked Dec 16 '22 13:12

zjffdu


2 Answers

Well, the value of n and d needs to be available somehow from inside the toString body, right? Otherwise you couldn't use them. Anything could happen between when you construct a new instance and n and d happen to be on the stack, and when you call toString, and n and p have long disappeared from the stack. So the compiler automatically saves the value in fields — even if you don't declare them as (private) vals in your code. The compiler will do so for all constructor variables that are used outside of the constructor of your classes (remember that the constructor of a class is actually the whole body of the class itself, excluding val and def definitions).

like image 159
Jean-Philippe Pellet Avatar answered Dec 28 '22 23:12

Jean-Philippe Pellet


Scala will take constructor arguments, even if not declared val or var and add them as private fields to a class if they ever need to be used outside of the constructor.

In your case, toString could be called long after object creation. So those parameters need to be stored in the constructed instance.

like image 21
Kevin Wright Avatar answered Dec 29 '22 00:12

Kevin Wright