Question

I have the following code defined (in Scala IDE/Scala Worksheet with Scala 2.10):

object WorkSheet1 {
  object A {
    def apply(s: String, huh: Boolean = false): A = A(s)
  }
  case class A (s: String)
  //case class A private (s: String)
  val a = A("Oh, Hai")
}

And I successfully receive the following output:

a : public_domain.WorkSheet1.A = A(Oh, Hai)

However, when I comment out the existing case class A (s: String) and uncomment out the other one (containing "private"), I receive the following compiler error: "constructor A in class A cannot be accessed in object WorkSheet1".

It was my understanding that a companion object had access to all of it's companion class's private parts. Heh. Uh...seriously, though. What gives?

Was it helpful?

Solution

Make it private for anybody but As

object WorkSheet1 {
  object A {
    def apply(s: String, huh: Boolean = false): A = A(s)
  }
  case class A private[A](s: String)
  val a = A("Oh, Hai", false)
}

I added false to solve ambiguity between object apply and case class constructor which is publicly visible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top