2011-08-02 69 views
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 
               ^

这是为什么发生?

回答

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._ 
您可以有几种方法解决这个问题
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>