111

在 Scala 2.8 中有没有办法重载案例类的构造函数?

如果是,请放一个片段来解释,如果不是,请解释为什么?

4

2 回答 2

200

重载构造函数对于案例类并不特殊:

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)
于 2010-03-08T12:15:20.123 回答
24

你可以用通常的方式定义一个重载的构造函数,但要调用它,你必须使用“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)
于 2010-03-08T12:11:13.363 回答