在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)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top