views:

141

answers:

2

Are there named constructors in Scala?

+3  A: 

Depends what you mean with "named constructors", but yes you can overload constructors see http://stackoverflow.com/questions/2400794/overload-constructor-for-scalas-case-classes

Also you can put factory methods in a Companion Objects for your class (static singleton).

oluies
+1  A: 

I don't think there are but the named constructor idiom can be supported by object methods calling class constructors. Typically in Scala the apply method is used as it can use function call syntax:

val mc = MyClass(a, b, c)

with the following definition

object MyClass {def apply(a: Atype, b: Btype, c: Ctype) = new MyClass(a, b, c)}

or if you want something like

val mc = MyClass.create(a, b, c)

it would be simply

object MyClass {def create(a: Atype, b: Btype, c: Ctype)  = new MyClass(a, b, c)}

You are not limited to the companion object either, however private and protected constructors would require you to use the companion object directly or as a proxy to access the class constructor(s),

Don Mackenzie