Scala的Case Classes的重载构造函数? [英] Overload constructor for Scala's Case Classes?
本文介绍了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)
这篇关于Scala的Case Classes的重载构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文