来自 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
^
为什么会这样?