Don Mackenzie
Don Mackenzie

Reputation: 7963

Private and protected constructor in Scala

I've been curious about the impact of not having an explicit primary constructor in Scala, just the contents of the class body.

In particular, I suspect that the private or protected constructor pattern, that is, controlling construction through the companion object or another class or object's methods might not have an obvious implementation.

Am I wrong? If so, how is it done?

Upvotes: 114

Views: 36760

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297295

Aleksander's answer is correct, but Programming in Scala offers an additional alternative:

sealed trait Foo {
 // interface
}

object Foo {
  def apply(...): Foo = // public constructor

  private class FooImpl(...) extends Foo { ... } // real class
}

Upvotes: 65

Aleksander Kmetec
Aleksander Kmetec

Reputation: 3327

You can declare the default constructor as private/protected by inserting the appropriate keyword between the class name and the parameter list, like this:

class Foo private () { 
  /* class body goes here... */
}

Upvotes: 199

Related Questions