我正在尝试深入了解 Scala 语言,并认为最好的学习方法是将其付诸实践。当在 Java 项目(Spring)和我的 Scala 项目之间复制粘贴代码时,IDE 进行了我不理解的转换。不幸的是,在互联网和文档中搜索它并没有给我带来任何帮助。
代码:
@Bean private[context] def passwordEncoder: PasswordEncoder = {
return new BCryptPasswordEncoder
}
编译上述代码时,编译器提示:
`error: context is not an enclosing class`
有人能解释一下private[context]
部分的含义吗?
最佳答案
context
只是一个占位符,您可以在其中填写您希望该方法为私有(private)的上下文。但这是可选的。如果不指定上下文,该成员将变为“类私有(private)”,据我所知,其行为类似于 Java 中的 private
。
背景:Scala 提供了不止一种程度的访问规范:对象私有(private)规范,即 private[this]
,规定所讨论的成员只能由调用该成员的成员看到对象,而不是来自不同的对象,即使它们属于同一类型。除了 this
,您还可以使用包名称甚至 root
,它是根命名空间的别名。
有关此内容的更多信息,请参阅 Scala Language Reference 的“第 5.2 节 - 修饰符” :
The private modifier can be used with any definition or declaration in a template.
[...]
The 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 (§5.4).
关于scala - private 的含义是什么[上下文],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975670/