我试图指定 val
常量仅对一个对象可见:
object Config {
private[my.pack.MyObject] val Some = Option("String")
}
// in package my.pack
object MyObject {
val Other = Config.Some
}
编译时出现错误:
[error] C:\path\Config.scala:17: ']' expected but '.' found.
[error] private[my.pack.MyObject] val Some = Option("String")
[error] ^
怎么了?当我读到访问限定符时,它们可以是类或对象,而不是包,我错了吗?
最佳答案
来自 the Scala Language specification, section 5.2.1 :
A private modifier can be qualified with an identifier C (e.g.
private[C]
) that must denote a class or package enclosing the definition. Members labeled with such a modifier are accessible respectively only from code inside the package C or only from code inside the class C and its companion module.
(大胆的我——注意“类或包”也承认“对象”,不确定这是规范中的标准语言,还是规范中的错误)
因此您的示例无法编译,因为 my.pack.MyObject
不是 val Some
的封闭声明。
关于scala - 如何将 Scala 私有(private)范围限制为仅一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32294741/