为什么我的嵌套伴生对象的成员在类中不自动可见?
假设我有这个 Scala 代码:
object Outer {
object Inner {
val B = "B"
}
class Inner {
def b = B
}
}
我希望它能够编译,但是无法从 b
的定义访问 B
。我需要在 class Inner
中添加 import Inner._
才能使其正常工作。这是为什么?伴生对象 Inner
是否未正确定义?
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 Inner
to make it work. Why is that? Is the companion object Inner
not defined correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果将伴生对象的成员导入到类中,则会污染类的名称空间,而程序员无法控制它。对于值来说,这可能没那么糟糕(但仍然很糟糕),但我真的不想看到函数出现这种情况。
想想
apply()
或从特征继承的函数(这两种情况都不能只更改名称而不丢失某些内容)。如果这些函数自动导入到类命名空间中,编译器将不知道使用哪一个。因此,如果类和对象有一个函数func()
,您最终会在类代码中编写this.func()
只是为了确定调用哪个函数。因此,将其视为保持命名空间清洁的一种可能性。您仍然可以使用
import Inner._
来污染它If the members of the companion object would be imported into the class, it would pollute the namespace of the class without the programmer being able to controle it. This might not be that bad (but still bad) with values but I really wouldn't want to see that with functions.
Just think about
apply()
or functions you inherit from traits (both cases where you can't just change the name without loosing something). If these functions where automatically imported into your classes namespace, the compiler wouldn't know which one to use. So if the class and the object had a functionfunc()
you would end up writingthis.func()
in your classes code just to make sure which one to call.So see it as a possibility to keep your namespace clean. You can still pollute it by using
import Inner._
它只是不应该以这种方式工作 - 使用
import Inner._
是一致的行为。一般来说,如果要实现类似于Java中静态成员的行为,就需要伴生对象。 Scala 方法是将所有静态成员移至单例对象,其优点是可以从中访问伴生类的私有/受保护成员:
您可以使用伴生对象作为具有私有构造函数的类的工厂:
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: