Suppose I have this Scala code:
object Outer {
object Inner {
val B = "B"
}
class Inner {
def b = B
}
}
I would expect this to compile, but B cannot be accessed from the definition of b. I need to add import Inner._ in class Innerto make it work. Why is that? Is the companion object Inner not defined correctly?
It’s just not supposed to work this way – using
import Inner._is a consistent behavior.Generally, companion object is needed, if you want to achieve the behavior similar to static members in Java. Scala way is to move all static members away to a singleton object, with the benefit that private/protected memebers of a companion class can be accessed from it:
You can use companion object as a factory for the class with a private constructor: