Scala 构造函数重载? [英] Scala constructor overload?

查看:77
本文介绍了Scala 构造函数重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Scala 中提供重载构造函数?

How do you provide overloaded constructors in Scala?

推荐答案

值得明确提及的是,Scala 中的辅助构造函数必须调用主构造函数(如在landon9720 中的)答案,或者来自同一类的另一个辅助构造函数,作为它们的第一个动作.它们不能像在 Java 中那样简单地显式或隐式调用超类的构造函数.这确保主构造函数是该类的唯一入口点.

It's worth explicitly mentioning that Auxiliary Constructors in Scala must either call the primary constructor (as in landon9720's) answer, or another auxiliary constructor from the same class, as their first action. They cannot simply call the superclass's constructor explicitly or implicitly as they can in Java. This ensures that the primary constructor is the sole point of entry to the class.

class Foo(x: Int, y: Int, z: String) {  
  // default y parameter to 0  
  def this(x: Int, z: String) = this(x, 0, z)   
  // default x & y parameters to 0
  // calls previous auxiliary constructor which calls the primary constructor  
  def this(z: String) = this(0, z);   
}

这篇关于Scala 构造函数重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆