gpt4 book ai didi

scala - 如何将 Scala 私有(private)范围限制为仅一个对象?

转载 作者:行者123 更新时间:2023-12-01 10:38:09 24 4
gpt4 key购买 nike

我试图指定 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com