伴生对象无法访问类上的私有变量
来自 Scala REPL 的相当奇怪的行为。
尽管以下编译没有问题:
class CompanionObjectTest {
private val x = 3
}
object CompanionObjectTest {
def testMethod(y:CompanionObjectTest) = y.x + 3
}
私有变量似乎无法从 REPL 中的伴生对象访问:
scala> class CompanionObjectTest {
|
| private val x = 3;
| }
defined class CompanionObjectTest
scala> object CompanionObjectTest {
|
| def testMethod(y:CompanionObjectTest) = y.x + 3
| }
<console>:9: error: value x in class CompanionObjectTest cannot be accessed in CompanionObjectTest
def testMethod(y:CompanionObjectTest) = y.x + 3
^
为什么会发生这种情况?
A rather weird behavior coming from the Scala REPL.
Although the following compiles without a problem:
class CompanionObjectTest {
private val x = 3
}
object CompanionObjectTest {
def testMethod(y:CompanionObjectTest) = y.x + 3
}
the private variable does not seem to be accessible from the companion object in REPL:
scala> class CompanionObjectTest {
|
| private val x = 3;
| }
defined class CompanionObjectTest
scala> object CompanionObjectTest {
|
| def testMethod(y:CompanionObjectTest) = y.x + 3
| }
<console>:9: error: value x in class CompanionObjectTest cannot be accessed in CompanionObjectTest
def testMethod(y:CompanionObjectTest) = y.x + 3
^
Why is that happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所发生的情况是,REPL 上的每条“行”实际上都放置在不同的包中,因此类和对象不会成为同伴。您可以通过多种方式解决此问题:
进行链类和对象定义:
使用粘贴模式:
将所有内容放入对象内:
What is happening is that each "line" on REPL is actually placed in a different package, so the class and the object do not become companions. You can solve this in a few ways:
Make chain class and object definitions:
Use paste mode:
Put everything inside an object:
这确实有点奇怪。要解决此问题,您应该首先使用
:paste
进入粘贴模式,然后定义您的类和伴生对象,并使用 CTRL-D 退出粘贴模式。下面是一个 REPL 会话示例:This is indeed a little weird. To work around this problem, you should enter paste mode first with
:paste
, then define your class and your companion object and exit paste mode with CTRL-D. Here is a sample REPL session: