A rather weird behavior coming from the Scala REPL.
Although the following compiles without a problem:
class CompanionObjectTest {
private val x = 3
}
object CompanionObjectTest {
def testMethod(y:CompanionObjectTest) = y.x + 3
}
the private variable does not seem to be accessible from the companion object in 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
^
Why is that happening?
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:What is happening is that each "line" on REPL is actually placed in a different package, so the class and the object do not become companions. You can solve this in a few ways:
Make chain class and object definitions:
Use paste mode:
Put everything inside an object: