Scala的Case Classes的重载构造函数?

Fel*_*lix 99 constructor scala overloading case-class scala-2.8

在Scala 2.8中是否有一种方法来重载案例类的构造函数?

如果是的话,请把一个片段解释一下,如果没有,请解释原因?

ret*_*nym 187

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

case class Foo(bar: Int, baz: Int) {
  def this(bar: Int) = this(bar, 0)
}

new Foo(1, 2)
new Foo(1)
Run Code Online (Sandbox Code Playgroud)

但是,您可能还希望重载apply伴随对象中的方法,该方法在省略时调用new.

object Foo {
  def apply(bar: Int) = new Foo(bar)
}

Foo(1, 2)
Foo(1)
Run Code Online (Sandbox Code Playgroud)

在Scala 2.8中,通常可以使用命名和默认参数而不是重载.

case class Baz(bar: Int, baz: Int = 0)
new Baz(1)
Baz(1)
Run Code Online (Sandbox Code Playgroud)

  • Martin Odersky解释了为什么不自动添加额外的应用方法:http://www.scala-lang.org/node/976 (10认同)
  • 我如何在重载的构造函数中使用局部变量?例如:`def this(bar:Int)= {val test = 0; 这个(吧,测试)}`(这不起作用) (2认同)

Luk*_*ytz 21

您可以通常的方式定义重载的构造函数,但要调用它,您必须使用"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)
Run Code Online (Sandbox Code Playgroud)

  • 这不是严格正确的 - 您可以像往常一样在伴随对象中声明它 (2认同)