Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload constructor for Scala's Case Classes?

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?

like image 704
Felix Avatar asked Mar 08 '10 11:03

Felix


People also ask

Can you overload a class constructor?

Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.

Can case class be extended?

The answer is simple: Case Class can extend another Class, trait or Abstract Class. Create an abstract class which encapsulates the common behavior used by all the classes inheriting the abstract class.

Can case classes have methods Scala?

Case Classes You can construct them without using new. case classes automatically have equality and nice toString methods based on the constructor arguments. case classes can have methods just like normal classes.


1 Answers

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) 
like image 116
retronym Avatar answered Oct 14 '22 03:10

retronym