8

ScalaREPLから来るかなり奇妙な振る舞い。

以下は問題なくコンパイルされますが:

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 に答える