Super Powers to Qualified Access Modifiers

Scala uses access modifiers quite differently from Java. Let’s see what the differences are and why qualified access modifiers are so powerful in Scala.

default access modifier

Scala >> public
Java >> protected

While in Scala the public keyword doesn’t exist, Java allows you to explicitly use the keyword protected as you please.


Scala >> accessible from a class and its companion object
Java >> accessible from a class and its inner classes


Scala makes a special link between a class and its companion object, but not with inner classes as they are not accessible with a private modifier.


Scala >> accessible from a class and its subclasses
Java >> accessible from all the classes in the same package

Scala is quite restrictive here 😐 (but don’t worry too much, keep reading…)


Scala and Java >> accessible from everywhere

Finally something that works in the same way! 😀

So far, we could think that the access modifier system in Scala is more limited than the Java one. Actually, it is a lot more powerful than the Java one, thanks to the super powers of qualified access modifiers!

private[X] and protected[X]

By adding qualifiers to an access modifier we can redefine its visibility. In the following definitions, X can be a package, an object or a class:

private[X] >> private and accessible from X
protected[X] >> protected and accessible from X

We can use this technique to obtain exactly the same meaning of the Java access modifiers:

– Java private member in class MyClass becomes Scala private[MyClass] member
– Java protected member in package girlcoding becomes Scala protected[girlcoding] member


We can also declare a member as object-private:

private[this] >> accessible only for the instance that contains the definition/field

This makes sure that the member will not be visible to other objects of the same class…it’s like a super private modifier! 😀

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s