Companion对象无法访问类上的私有变量

时间:2011-08-02 23:30:00

标签: scala read-eval-print-loop companion-object

来自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
                                                 ^

为什么会这样?

2 个答案:

答案 0 :(得分:13)

发生的事情是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._

答案 1 :(得分:2)

这确实有点奇怪。要解决此问题,您应首先使用:paste输入粘贴模式,然后使用CTRL-D定义您的类和随播对象并退出粘贴模式。以下是REPL会话示例:

Welcome to Scala version 2.9.0.1 (OpenJDK Server VM, Java 1.6.0_22).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class A { private val x = 0 }
object A { def foo = (new A).x }

// Exiting paste mode, now interpreting.

defined class A
defined module A

scala>