Scala的Case Classes的重载构造函数?
问题描述:
在Scala 2.8中有一种方法来重载一个case类的构造函数?
In Scala 2.8 is there a way to overload constructors of a case class?
如果是,请放一个代码片段解释,如果没有,请解释一下为什么?
If yes, please put a snippet to explain, if not, please explain why?
答
重载构造函数对于案例类不是特殊的:
Overloading constructors isn't special for case classes:
case class Foo(bar: Int, baz: Int) {
def this(bar: Int) = this(bar, 0)
}
new Foo(1, 2)
new Foo(1)
您可能还想重载伴随对象中的 apply
方法,当您省略 new
时调用该方法。 p>
However, you may like to also overload the apply
method in the companion object, which is called when you omit new
.
object Foo {
def apply(bar: Int) = new Foo(bar)
}
Foo(1, 2)
Foo(1)
In Scala 2.8, named and default parameters can often be used instead of overloading.
case class Baz(bar: Int, baz: Int = 0)
new Baz(1)
Baz(1)