开发者

Named constructors in Scala?

Are there named开发者_如何学运维 constructors in Scala?


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).


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),

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜