Konstantin Milyutin
Konstantin Milyutin

Reputation: 12366

Object-private variables implementation

I'm trying to understand implementation of object-private variables in Scala. Scala compiles this class

class Counter{
    private[this] var age = 0
}

into the following java byte code:

public class Counter implements scala.ScalaObject {
  private int age;
  public Counter();
}

But still, because JVM doesn't support object-private fields, we have good-old private field, which can be accessed from other instances of the class. So for me the difference between previous class and the following in terms of hiding private field is not clear.

class Counter2{
    private var age = 0
}

public class Counter2 implements scala.ScalaObject {
  private int age;
  private int age();
  private void age_$eq(int);
  public Counter2();
}

Upvotes: 1

Views: 245

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

The JVM is irrelevant. The semantics of Scala are implemented by the Scala compiler, not the JVM. After all, the JVM isn't even the only platform Scala runs on, there are production-ready implementations of Scala on the CLI, and experimental ones on ECMAScript as well as a native one.

Upvotes: 1

Related Questions