Scala 构造函数过载? ?

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

69997 次浏览
 class Foo(x: Int, y: Int) {
def this(x: Int) = this(x, 0) // default y parameter to 0
}

值得明确提及的是,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);
}

在 Scala 2.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)

具有默认值的参数必须排在参数列表中没有默认值的参数之后。

在查看我的代码时,我突然意识到我在某种程度上重载了一个构造函数。然后我想起了这个问题,回来给出了另一个答案:

在 Scala 中,你不能重载构造函数,但是你可以使用函数。

另外,许多人选择将伴随对象的 apply函数作为相应类的工厂。

将这个类抽象并重载 apply函数来实现——实例化这个类,你就有了重载的“构造函数”:

abstract class Expectation[T] extends BooleanStatement {
val expected: Seq[T]
…
}


object Expectation {
def apply[T](expd:     T ): Expectation[T] = new Expectation[T] {val expected = List(expd)}
def apply[T](expd: Seq[T]): Expectation[T] = new Expectation[T] {val expected =      expd }


def main(args: Array[String]): Unit = {
val expectTrueness = Expectation(true)
…
}
}

注意,我显式地将每个 apply定义为返回 Expectation[T],否则它将返回一个 Duck 类型的 Expectation[T]{val expected: List[T]}

试试这个

class A(x: Int, y: Int) {
def this(x: Int) = this(x, x)
def this() = this(1)
override def toString() = "x=" + x + " y=" + y
class B(a: Int, b: Int, c: String) {
def this(str: String) = this(x, y, str)
override def toString() =
"x=" + x + " y=" + y + " a=" + a + " b=" + b + " c=" + c
}
}