如何在Scala中提供重载构造函数?
发布于 2009-07-08 07:10:04
值得一提的是,Scala中的辅助构造函数必须调用主构造函数(就像landon9720的答案一样),或者调用同一类中的另一个辅助构造函数作为它们的第一个操作。它们不能像在Java中那样显式或隐式地调用超类的构造函数。这确保了主构造函数是该类的唯一入口点。
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);
}
发布于 2009-07-07 23:16:55
class Foo(x: Int, y: Int) {
def this(x: Int) = this(x, 0) // default y parameter to 0
}
发布于 2010-12-12 09:31:15
从Scala2.8.0开始,你还可以设置构造器参数和方法参数的默认值。像这样
scala> class Foo(x:Int, y:Int = 0, z:Int=0) {
| override def toString() = { "Foo(" + x + ", " + y + ", " + z + ")" }
| }
defined class Foo
scala> new Foo(1, 2, 3)
res0: Foo = Foo(1, 2, 3)
scala> new Foo(4)
res1: Foo = Foo(4, 0, 0)
在参数列表中,具有默认值的参数必须位于没有默认值的参数之后。
https://stackoverflow.com/questions/1095329
复制相似问题