chaotic3quilibrium
chaotic3quilibrium

Reputation: 5924

In Scala, how do I access a case class's private constructor from its companion object

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?

Upvotes: 1

Views: 1983

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62855

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.

Upvotes: 5

Related Questions