伴随对象无法访问类上的私有变量 [英] Companion object cannot access private variable on the class
本文介绍了伴随对象无法访问类上的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
来自 Scala REPL 的一个相当奇怪的行为.
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
}
似乎无法从 REPL 中的伴随对象访问私有变量:
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
^
为什么会这样?
推荐答案
发生的事情是 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:
制作链类和对象定义:
scala> class CompanionObjectTest {
| private val x = 3;
| }; object CompanionObjectTest {
| def testMethod(y:CompanionObjectTest) = y.x + 3
| }
defined class CompanionObjectTest
defined module CompanionObjectTest
使用粘贴模式:
scala> :paste
// Entering paste mode (ctrl-D to finish)
class CompanionObjectTest {
private val x = 3
}
object CompanionObjectTest {
def testMethod(y:CompanionObjectTest) = y.x + 3
}
// Exiting paste mode, now interpreting.
defined class CompanionObjectTest
defined module CompanionObjectTest
把所有东西都放在一个对象里:
Put everything inside an object:
scala> object T {
| class CompanionObjectTest {
| private val x = 3
| }
| object CompanionObjectTest {
| def testMethod(y:CompanionObjectTest) = y.x + 3
| }
| }
defined module T
scala> import T._
import T._
这篇关于伴随对象无法访问类上的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文