1

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?

chaotic3quilibrium
  • 5,661
  • 8
  • 53
  • 86

1 Answers1

5

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.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • Thank you. It does appear that adding "[A]" resolved the compiler error. However, why is the compiler complaining of an ambiguity without the adding of the "false" when the val a only has access to object A.apply (and shouldn't see or be impacted by the case class constructor)? – chaotic3quilibrium Oct 04 '13 at 21:34
  • You could use [`DummyImplicit`](http://www.scala-lang.org/api/current/index.html#scala.Predef$$DummyImplicit) instead of your dummy Boolean value. – DaoWen Oct 05 '13 at 01:33
  • 2
    Or change `A(s)` to `new A(s)` to be explicit about wanting to call the constructor and not the `apply` – theon Oct 05 '13 at 16:38