Can't get an access to a companion object's field

You can do that by using MyClass.val1 instead of just val1. I guest that's done to denote that companion object members can be accessed from anywhere (with default modifiers).


It's debatable that a class "should" have access to its companion object fields by default. Consider the not uncommon case where the companion object's apply method is used as a factory, and the object itself has an apply method to do something different. It would get confusing to read the code and know which method was meant! Roland Ewald made a comment to another answer quoting http://www.scala-lang.org/old/node/2411.html#comment-8493 which sums it up nicely:

"The thing is, it's a lot easier to import something into your namespace if you want it than it is to unimport if you don't. And personally I already have enough problems with shadowing."

And that gives the answer. Use import thus:

class MyClass {
  import MyClass._
  println(val1) // Should see it now!
}

object MyClass {
  val val1 = "str"
}