By Alvin Alexander. Last updated: November 28, 2023
As a brief note, the Scala example at this URL (www.geeksforgeeks.org/controlling-method-scope-in-scala/) is not 100% correct, and this code Scala 3 code shows the issue and solution:
package a: class ClassA: protected var aProtected = 1 var a = 1 package b: import a.ClassA class ClassB extends ClassA: a = 2 aProtected = 2 // ClassB *can* access this field. def getAProtected = aProtected // make that field available to others // via this public method. object Main: def main(args: Array[String]): Unit = val b = ClassB() b.a b.getAProtected // compiles/works // b.aProtected // does not compile
They correctly note that the variable I call aProtected
can’t be accessed from the main method in the second package, but aProtected
can be accessed by ClassB
, which extends ClassA
, though ClassB
is in package b
and ClassA
is in package a
.
So if you wanted to see an example of how to access a protected field in Scala code, where your class extends a class in a different package, and that original class has a protected field, I hope this example is helpful.