Are there named constructors in Scala?
Named constructors in Scala?
651 Views Asked by Łukasz Lew At
2
There are 2 best solutions below
0

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),
Depends what you mean with "named constructors", but yes you can overload constructors see Overload constructor for Scala's Case Classes?
Also you can put factory methods in a Companion Objects for your class (static singleton).