Overload constructor for Scala's Case Classes?

ScalaConstructorOverloadingScala 2.8Case Class

Scala Problem Overview


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?

Scala Solutions


Solution 1 - Scala

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)

Solution 2 - Scala

You can define an overloaded constructor the usual way, but to invoke it you have to use the "new" keyword.

scala> case class A(i: Int) { def this(s: String) = this(s.toInt) }
defined class A

scala> A(1)
res0: A = A(1)

scala> A("2")
<console>:8: error: type mismatch;
 found   : java.lang.String("2")
 required: Int
       A("2")
         ^

scala> new A("2")
res2: A = A(2)

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
QuestionFelixView Question on Stackoverflow
Solution 1 - ScalaretronymView Answer on Stackoverflow
Solution 2 - ScalaLukas RytzView Answer on Stackoverflow