8

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

为什么会这样?

4

2 回答 2

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._
于 2011-08-02T23:54:56.160 回答
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> 
于 2011-08-02T23:36:20.563 回答