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 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) val
s 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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With