来自 Scala REPL 的一个相当奇怪的行为。
尽管以下编译没有问题:
class CompanionObjectTest {
private val x = 3
}
object CompanionObjectTest {
def testMethod(y:CompanionObjectTest) = y.x + 3
}
私有(private)变量似乎无法从 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 上的每一“行”实际上都放在不同的包中,因此类和对象不会成为伙伴。您可以通过以下几种方式解决此问题:
制作链类和对象定义:
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
将所有内容放入对象中:
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._
关于scala - 伴侣对象无法访问类上的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919965/