1

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();
}
3
  • possible duplicate of private[this] vs private Commented May 9, 2013 at 7:46
  • What is your question? The obvious difference is that it is a compile-time error for another instance to access the object-private field. But I assume you know that, so I am not sure what is being asked here. Commented May 9, 2013 at 9:47
  • My question is how it is implemented, if JVM doesn't support object-private fields Commented May 9, 2013 at 9:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

so Scala compiler forbids all access to object-private fields, except those accessed through this? is it correct?
It's worth noting that even the Java compiler sometimes produces bytecode that allows access to private variables and methods. For example, if an inner class accesses a private variable in its outer class. The reason is the same as for Scala - the JVM's data model isn't a perfect fit with the data models in either Scala or the latest versions of Java, so the compiler cheats a little bit.
And of course almost all JVMs eventually compile to native code, which doesn't know anything about objects, classes, interfaces, public, private, protected, methods, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.