如何在 Scala 中将包设为私有?

How do I make a package in Scala private?

如果我在 Scala 中有这样的包层次结构:

package toplevel {
  package a {
    // some interesting stuff
  }

  package b {
    // more interesting stuff
  }

  package utility {
    // stuff that should not be accessible from the outside
    // and is not logically related to the project,
    // basically some helper objects
  }
}

如何禁止包 toplevel 的用户查看或导入包 utility

我尝试使用 private[toplevel] package utility { ... 但出现此错误:expected start of definition

我已经搜索过这个并且被误报淹没了:我得到的一切都是关于使事情包私有的,这不是我的问题。

要达到与 Java 中私有包相同的目标,您可以使用增强的访问修饰符。在您的包实用程序中,您使用 private[utility] 限制访问。这样,包成员仅在包实用程序本身内部可用。

希望对您有所帮助。

    You can only define the enclosing package, within which the code is defined

Answered 这里

你不能:包没有访问级别。

或者更确切地说,您可以使用 OSGi 而不是导出它们,但如果您出于其他原因不需要它,那么这是一个非常重量级的解决方案。