11 February, 2014

Access Modifiers in Scala for Java programmers

   Today I’m going to concisely compare Scala's access modifiers with these used in Java. For more detailed description please refer to this post.

Java access modifiers:

Scala access modifiers:


Additionally in Scala private and protected access modifiers can be qualified with a name of a package or class. This is done using square brackets e.g.
For class defined in package a.b.c 
  • protected[c] will be the same as protected in Java
  • private[c] will be the same as default in Java
You can also use other packages that are available in class’s package tree:
  • protected[a] will be visible in subclasses and in packages a, b and c (package a and all its subpackages)
  • private[b] will be visible in packages b and c
  • for class defined in package a.b it is not allowed to define private[c] or protected[c]
Inner class in Scala has access to private members of enclosing class, but enclosing class doesn’t have access to private members of inner class.
class Enclosing {
 private val x = 5
 new Inner().z // value z in class Inner cannot be accessed in Enclosing.this.Inner 
 class Inner {
   private val z = 9
   def out = x + z // no problem
 }
}
If you want to make it work similarly to Java you need to add enclosing class qualifier.
   private[Enclosing] val z = 9

The last scope introduce in Scala that is worth to mention is the object private:
   private[this] val member = 1
which stipulates that the member can only be seen by members called on that same object, not from different objects, even if they are of the same type.

No comments:

Post a Comment