File bound packages; a heresy?

I understood the question to be whether a top-level definition can be made private to the file, and the answer is no, or rather a qualified no. (pun alert)

There was discussion somewhere about whether it should work that way, several years ago.

Since top-level defs are members of a file-specific “package object”, intuitively one might expect private[this] to do the trick, but that syntax is no longer supported.

The qualification is that TIL the following does work in file priv1.scala:

def trial() = 27 //+ p.f

package p:

  //private def f = 42
  //private[p] def f = 42
  private[priv1$package] def f = 42 // visible only to top-level defs in this file
  def g = f

  class C:
    def g = 42
    //def g = f // disallowed

IIRC the naming of the package object is specified, although use of $ in source code names is discouraged.

The qualified private package member is not accessible from other files, as desired.

A related behavior is that definitions in the “unnamed package” can access definitions in a named package but not conversely. I see that the unnamed package cannot access package-private definitions, however, even if they are in the same file.

Similar glitches in “lexical scoping” are visible with opaque types that are “top-level”, such that what you see (as a hierarchy of scopes in the source text) is not exactly what you get.

2 Likes