Greg
Greg

Reputation: 11512

How can a class and companion object see private vals in Scala?

object Foo {
  private val thing: String = "Yay"
}

case class Foo() {
  println(thing)
}

Is it possible for object Foo's thing to be visible only in class instances of Foo (shared visibility)? As shown, compiler complains

...thing in class is unresolved.

I'd rather not open it up to package-level visibility if it can be avoided.

Upvotes: 1

Views: 219

Answers (1)

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

You need to import members of object Foo inside case class:

object Files {

  object Foo {
    private val thing: String = "Yay"
  }

  case class Foo() {
    import Foo._
    println(thing) //ok
  }
}

Using qualified name Foo.thing without import would also work.

Upvotes: 5

Related Questions