Overload constructor for Scala's Case Classes?

Felix picture Felix · Mar 8, 2010 · Viewed 68.2k times · Source

In Scala 2.8 is there a way to overload constructors of a case class?

If yes, please put a snippet to explain, if not, please explain why?

Answer

retronym picture retronym · Mar 8, 2010

Overloading constructors isn't special for case classes:

case class Foo(bar: Int, baz: Int) {
  def this(bar: Int) = this(bar, 0)
}

new Foo(1, 2)
new Foo(1)

However, you may like to also overload the apply method in the companion object, which is called when you omit new.

object Foo {
  def apply(bar: Int) = new Foo(bar)
}

Foo(1, 2)
Foo(1)

In Scala 2.8, named and default parameters can often be used instead of overloading.

case class Baz(bar: Int, baz: Int = 0)
new Baz(1)
Baz(1)