Reputation: 4699
A trait cannot be instantiated. Hence, its fields can only be accessed by classes/traits/objects extending it. Hence, these two pieces of code are effectively the same:
trait foo{
protected val fish:String
}
class bar extends foo{
val fish = "catfish"
}
and
trait foo{
val fish:String
}
class bar extends foo{
val fish = "catfish"
}
The protected
access modifier is redundant for traits then. Right?
Upvotes: 0
Views: 930
Reputation: 179119
It's redundant only because in the first version you've changed the visibility of the member from protected
to public
in the implementing class (by not marking it as protected
). If you don't do that, then you can see that defining a member as protected
in a trait means that a class has to implement it, but not expose it through its public API.
trait Foo {
protected val fish: String
}
class Bar extends Foo {
override protected val fish = "catfish"
}
val bar = new Bar
bar.fish // not visible
Upvotes: 4