Scala 趣题 19 包名和对象名等不能重


package pzs

object base {
  class X { val context = "object base" }
}

package base {
  class Y { val context = "package base" }
}

object Main extends App {
  println((new base.X).context)
  println((new base.Y).context)
}





Explanation


According to the SLS (§9.2) it is illegal to have a package with the same fully qualified name as a module or a class. For example, on the following compilation unit


package com.scalapuzzlers

object base { class X }

package base { class X }


the compiler will report an error:


X.scala:3: error: base is already defined as object base

package base { class X }

        ^

one error found


Top-level definitions outside a packaging however are assumed to be injected into a special empty package. That package can neither be named nor imported, but the members of the empty package are visible to each other without qualification.


The example above defines the package base and the top-level object <empty>.base, where the latter is visible without qualification, i.e. the object shadows the package. Thus the first println statement would compile fine and print object base. The access to base.Y in the second println statement leads to the compiler error type Y is not a member of object base.


Class Y in package base can be accessed with a full qualified identifier:


println((new _root_.base.Y).context)


Members of the empty package are however only visible from within the empty package, i.e. only from other top-level classes. In all other packages, top-level objects and classes are not accessible. Real projects will thus never use top-level classes. 


你可能感兴趣的:(scala)