You’ve already seen a few modifiers in action, but let’s look deeper into them. Along with standard modifiers like private and protected, Scala has more modifiers and new abilities.
The private modifier can be used with any definition, which means it’s only accessible in an enclosed class, its companion object, or a companion class. In Scala, you can qualify a modifier with a class or a package name. In the following example, the private modifier is qualified by class and package name:
- package outerpkg.innerpkg
- class Outer {
- class Inner {
- private[Outer] def f() = "This is f"
- private[innerpkg] def g() = "This is g"
- private[outerpkg] def h() = "This is h"
- }
- }
The protected modifier is applicable to class member definitions. It’s accessible to the defining class and its subclasses. It’s also accessible to a companion object of the defining class and companion objects of all the subclasses. Like the private modifier, you can also qualify the protected modifier with class, package, and this. By default, when you don’t specify any modifier, everything is public. Scala doesn’t provide any modifier to mark members as public.
Like Java, Scala also provides an override modifier, but the main difference is that in Scala the override modifier is mandatory when you override a concrete member definition from the parent class. The overridemodifier can be combined with an abstract modifier, and the combination is allowed only for members of traits. This modifier means that the member in question must be mixed with a class that provides the concrete implementation. An example will demonstrate this fact. The following creates a DogMood trait (dogs are moody, you know) with an abstract greet method and an AngryMood trait that overrides it:
- trait DogMood{
- def greet
- }
- trait AngryMood extends DogMood {
- override def greet = {
- println("bark")
- super.greet
- }
- }
- trait AngryMood extends DogMood {
- abstract override def greet = {
- println("bark")
- super.greet
- }
- }
- trait DogMood{
- def greet
- }
- trait AngryMood extends DogMood {
- abstract override def greet = {
- printf("Bark ~~ ")
- super.greet
- }
- }
- class ADog extends DogMood{
- override def greet = { println("Wow---") }
- }
- class BDog extends ADog with AngryMood
- val bdog = new BDog()
- bdog.greet // Bark ~~ Wow---
- sealed trait QueryOption
Supplement
* Scala's Stackable Trait Pattern