过载构造函数Scala的case类?
-
18-09-2019 - |
题
在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)
不隶属于 StackOverflow