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);
}
Well, the value of
nanddneeds to be available somehow from inside thetoStringbody, right? Otherwise you couldn’t use them. Anything could happen between when you construct a new instance andnanddhappen to be on the stack, and when you calltoString, andnandphave 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, excludingvalanddefdefinitions).