Reputation: 17361
I'm trying to wrap my head around the Scala language and figured the best way to learn is to put it into practice. When copy pasting code between a Java project (Spring) and my Scala project the IDE did a conversion I do not understand. Searching for it on the internet and in the docs gave me nothing to work with unfortunately.
The code:
@Bean private[context] def passwordEncoder: PasswordEncoder = {
return new BCryptPasswordEncoder
}
When compiling the above code the compiler complains:
`error: context is not an enclosing class`
Can anybody explain what the private[context]
part means?
Upvotes: 2
Views: 706
Reputation: 25781
context
is just a placeholder, where you can fill in the context in which you'd like the method to be private. This is optional though. If you don't specify the context, the member becomes "class-private", which afaik behaves like private
does in Java.
Background: Scala offers more than one degree of access specification: the object-private specification, i.e. private[this]
, stipulates that the member in question can only be seen by members called on that same object, not from different objects, even if they are of the same type. Instead of this
you can also use a package name or even root
, which is an alias for the root namespace.
More information on this can be found in "Section 5.2 - Modifiers" of the Scala Language Reference:
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).
Upvotes: 4