A rather weird behavior coming from the Scala REPL.
Although the following compiles without a problem:
class CompanionObjectTest {
private val x
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:
scala> class CompanionObjectTest {
| private val x = 3;
| }; object CompanionObjectTest {
| def testMethod(y:CompanionObjectTest) = y.x + 3
| }
defined class CompanionObjectTest
defined module CompanionObjectTest
Use paste mode:
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
Put everything inside an object:
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._