- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
protected class with same name as enclosing package
Tue, 2011-12-20, 22:19
I am trying to create a class with a constructor that is accessible
only within its enclosing package object. This seems to work:
package object foo1 {
class foo2 protected[foo1]
val x = new foo2 // constructor should be accessible here
}
object PackageTest {
def main(args: Array[String]) {
def func(a: foo1.foo2) {} // type should be accessible here
//val x = new foo1.foo2 // constructor should not be
accessible here
}
}
Now suppose I want the class to have same name as the enclosing
package object. In other words, I want to change the class name foo2
to foo1 above. When I tried that, it didn't work. Apparently the
"foo1" in "protected[foo1]" then refers to the class rather than the
package. I tried "protected[_root_.foo1]" to disambiguate, but the
compiler wouldn't accept that. Any suggestions? Thanks.
--Russ P.
What is an id? (not in the Freudian sense)
I was going to suggest rename on import, but it turns out that I (no expert) was surprised by the restrictions on what you can supply to the access modifier.
There may be an idiom that works (because I am no expert), but this shakes my faith in the mantra, "everything nests" (with the lemma, or assumption, that you can reference everything).
Probably you tried all this, too:
package pkgparent
// _root_ is a compiler directive, not a magic name?
// _root_ cannot be imported
// because who would want to rename com in com.acme
//import _root_.{pkgparent => parent}
// identifier expected but '{' found.
//import {pkgparent => par}
class Bar protected[pkgparent](val value: String)
//class Bar protected[parent](val value: String)
//class Bar protected[par](val value: String)
package object pkgname { pkgself =>
class Foo protected[pkgname]
import _root_.pkgparent.{pkgname => encloser}
import _root_.pkgparent.pkgname.{pkgname => enclosee}
//class pkgname private[encloser](val name: String)
//class pkgname private[pkgself](val name: String)
class pkgname (val name: String) {
def this() = this("Foo");
}
val instance = new Foo
val another = new enclosee("Hello")
val sample = new enclosee()
}
object PkgName extends App {
println("I ran")
import pkgname.{Foo, another, sample}
import pkgname.{pkgname => P}
//val f = new Foo
def use(x: Foo) { }
def use(x: P) = x.name
println(use(another))
println(use(sample))
}
On Tue, Dec 20, 2011 at 1:19 PM, Russ P. <russ.paielli@gmail.com> wrote: