Scala案例类复制方法的区别在于2.9和2.10之间

Mat*_*kko 6 scala case-class scala-2.10

以下代码在Scala 2.9.1中编译:

scala> case class Foo(a: String)(val b: Int = 1)
defined class Foo

scala> val foo = Foo("some")(2)
foo: Foo = Foo(some)

scala> foo.copy("another")()
res1: Foo = Foo(another)
Run Code Online (Sandbox Code Playgroud)

但是在2.10.3中我们得到以下错误:

scala> foo.copy("another")()
<console>:11: error: not enough arguments for method copy: (b: Int)Foo.
Unspecified value parameter b.
          foo.copy("another")()
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么这会改变吗?除了foo.copy("另一个")之外,我还想知道是否有一些聪明的方法可以做到这一点(foo.b)

Kev*_*ght 3

不幸的是,这是设计使然的:https ://issues.scala-lang.org/browse/SI-6068

像这样的案例类上的辅助参数块通常仅用于隐式。否则它们的用途有限,因为它们不参与模式匹配或(如您所见)复制操作。

  • 来自编译器的更好的错误消息或者甚至在“Foo”定义中的警告会很好。 (2认同)