To get companion object in Scala a class and it's companion object have to be defined in the same file. It looks like that's what you are doing, especially when you are not using interpreter.
However, when you interpret code line by line in Scala, it wraps it in additional anonymous object to allow expressions to be defined without explicit classes or objects in REPL (more here).
Here is an illustration of the wrapping problem:
Doesn't work:
$ scala
Welcome to Scala version 2.10.6 (OpenJDK 64-Bit Server VM, Java 1.8.0_222).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class A {
| private val privateVal = 1
| }
defined class A
scala> object A extends App{
| println(new A().privateVal)
| }
<console>:9: error: value privateVal in class A cannot be accessed in A
println(new A().privateVal)
^
Works if defined at the same time using :paste
:
scala> :paste
// Entering paste mode (ctrl-D to finish)
// Script A.scala
class A {
private val privateVal = 1
}
object A extends App{
println(new A().privateVal)
}
// Exiting paste mode, now interpreting.
defined class A
defined module A
BTW, I don't get this problem when running scala A.scala
. Perhaps I'm using different version or settings.
If you can't use paste mode, or can't make interpreter read the whole file at once, a workaround is to wrap your code in any object to force interpretation of a single code block:
scala> object Workaround {
| class A {
| private val privateVal = 1
| }
| object A extends App{
| println(new A().privateVal)
| }
| }
defined module Workaround
App
. – Alexey RomanovDelayedInit
is fancier. Anyways, OP's issue seems to have been resolved and was not really related to this. – sarveshseri