在Scala 2.8中,有没有一种方法来重载样例类的构造函数?
如果可以,请提供一个代码片段进行说明。如果不行,请解释为什么。
在Scala 2.8中,有没有一种方法来重载样例类的构造函数?
如果可以,请提供一个代码片段进行说明。如果不行,请解释为什么。
对于case类,重载构造函数并不特殊:
case class Foo(bar: Int, baz: Int) {
def this(bar: Int) = this(bar, 0)
}
new Foo(1, 2)
new Foo(1)
不过,你可能还想在伴生对象中重载apply
方法,当你省略new
关键字时就会调用该方法。
object Foo {
def apply(bar: Int) = new Foo(bar)
}
Foo(1, 2)
Foo(1)
在Scala 2.8中,命名参数和默认参数经常可以代替重载。
case class Baz(bar: Int, baz: Int = 0)
new Baz(1)
Baz(1)
你可以按照通常的方式定义一个重载构造函数,但是要调用它,你必须使用"new"关键字。
scala> case class A(i: Int) { def this(s: String) = this(s.toInt) }
defined class A
scala> A(1)
res0: A = A(1)
scala> A("2")
<console>:8: error: type mismatch;
found : java.lang.String("2")
required: Int
A("2")
^
scala> new A("2")
res2: A = A(2)
def this(bar: Int) = { val test = 0; this(bar,test) }
(这个方法不起作用)。 - HEXapply
方法。否则,当你尝试使用辅助构造函数时会出现错误,指示编译器期望使用主构造函数。 - pferrel