Private and protected constructor in Scala

Scala

Scala Problem Overview


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?

Scala Solutions


Solution 1 - Scala

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... */
}

Solution 2 - Scala

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDon MackenzieView Question on Stackoverflow
Solution 1 - ScalaAleksander KmetecView Answer on Stackoverflow
Solution 2 - ScalaDaniel C. SobralView Answer on Stackoverflow