Say in a scala file I define a class like
private class Test{}
what does the private here mean? In java you can't have a top level private class, which obviously makes sense. But private is syntactically valid in scala, hope someone can shed some light upon it.
You could specify package name for private
modifier to allow access to this class only from specified package. By default (without package specified) it is visible only for other members in the enclosing package.
$ cat > test.scala <<EOF
package myPackage {
private[myPackage] class Test
private object A extends Test
}
package otherPackage {
object B extends myPackage.Test
}
EOF
$ scalac test.scala
test.scala:7: error: class Test in package myPackage cannot be accessed in package myPackage
object B extends myPackage.Test
^
one error found
For instance you can access private
class from its companion object like this:
trait ITest
private class Test extends ITest
object Test {
def apply(): ITest = new Test
}
Test()
// ITest = Test@59e2abc3
Further clarification on examples:
package myPackage {
private class Test
private object A extends Test
object B extends myPackage.Test //Compile error: private class Test escapes its defining scope as part of type myPackage.Test
private object C extends myPackage.Test // works since C is also private
object Test {
def apply() = new Test //error: private class Test escapes its defining scope as part of type myPackage.Test
}
object Test2 {
def apply(): ITest = new Test //works as ITest is public
}
}
As long as instances of a private class do not escape the enclosing package scope it can be used within the package hierarchy. Companion objects accessing private classes has to be in same package hierarchy as well. With private[P]
- p
can be any package name that exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With