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

dim*_*sli 8 scala read-eval-print-loop companion-object

来自Scala REPL的一个相当奇怪的行为.

虽然以下编译没有问题:

class CompanionObjectTest {
    private val x = 3
}
object CompanionObjectTest {
    def testMethod(y:CompanionObjectTest) = y.x + 3
}
Run Code Online (Sandbox Code Playgroud)

私有变量似乎无法从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
                                                 ^
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Dan*_*ral 13

发生的事情是REPL上的每个"行"实际上放在一个不同的包中,因此类和对象不会成为伴侣.您可以通过以下几种方式解决此问题:

制作链类和对象定义:

scala> class CompanionObjectTest {
     |   private val x = 3;
     | }; object CompanionObjectTest {
     |   def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
defined class CompanionObjectTest
defined module CompanionObjectTest
Run Code Online (Sandbox Code Playgroud)

使用粘贴模式:

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
Run Code Online (Sandbox Code Playgroud)

将所有内容放在对象中:

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._
Run Code Online (Sandbox Code Playgroud)