2011-08-02 15 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> 
関連する問題