Companion object cannot access private variable on the class

后端 未结 2 838
無奈伤痛
無奈伤痛 2020-12-31 18:24

A rather weird behavior coming from the Scala REPL.

Although the following compiles without a problem:

class CompanionObjectTest {
    private val x          


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 19:00

    This is indeed a little weird. To work around this problem, you should enter paste mode first with :paste, then define your class and your companion object and exit paste mode with CTRL-D. Here is a sample REPL session:

    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> 
    

提交回复
热议问题