111
votes

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?

2
You could have a Scala singleton (with the object keyword, that is), and define your class as private within that singleton, and have methods of the singleton for constructing your objects.Paggas
@Paggas, unfortunately when you return an instance of a class marked private out of it's scope it won't compile, even when returned from a method of it's in scope companion object.Don Mackenzie
This is done quite profusely throughout the Scalaz source code. The concept is also known as an abstract algebraic data type.Tony Morris

2 Answers

195
votes

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

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
}