Search code examples
scalaconstructorfactoryprotected

Scala protected constructor and builder in companion object


I have some classes with a protected constructor and the factory method is inside the companion object of an abstract super class. As of Scala 2.9.0.RC4 this doesn't compile anymore. I have "fixed" the issue by making the constructors package protected. But I don't want other classes even inside the same package to be able to call the constructors.

So what should I?

sealed abstract class A
object A {
  //the factory method, returning either a B or C
  def apply(): A
}
class B protected (...) extends A
class C protected (...) extends A

Solution

  • You could make them private inner classes of the object.

    object A {
      private class B extends A
      private class C extends A
    }