41

为什么 Scala 不推荐使用没有参数列表的案例类?为什么编译器建议改为()用作参数列表?

编辑 :

有人请回答我的第二个问题... :|

4

2 回答 2

32

很容易不小心将无参数案例类错误地用作模式。

scala> case class Foo                                             
warning: there were deprecation warnings; re-run with -deprecation for details
defined class Foo

scala> (new Foo: Any) match { case Foo => true; case _ => false } 
res10: Boolean = false

代替:

scala> (new Foo: Any) match { case _: Foo => true; case _ => false } 
res11: Boolean = true

或更好:

scala> case object Bar                                               
defined module Bar

scala> (Bar: Any) match { case Bar => true; case _ => false }        
res12: Boolean = true

更新希望下面的脚本能够说明为什么空参数列表比已弃用的缺失参数列表更受欢迎。

scala> case class Foo() // Using an empty parameter list rather than zero parameter lists.
defined class Foo

scala> Foo // Access the companion object Foo
res0: Foo.type = <function0>

scala> Foo() // Call Foo.apply() to construct an instance of class Foo
res1: Foo = Foo()

scala> case class Bar
warning: there were deprecation warnings; re-run with -deprecation for details
defined class Bar

scala> Bar // You may expect this to construct a new instance of class Bar, but instead
           // it references the companion object Bar 
res2: Bar.type = <function0>

scala> Bar() // This calls Bar.apply(), but is not symmetrical with the class definition.
res3: Bar = Bar()

scala> Bar.apply // Another way to call Bar.apply
res4: Bar = Bar()

案例对象通常仍然比空参数列表更受欢迎。

于 2010-02-12T20:36:44.057 回答
20

Without parameters, every instance of the case class is indistinguishable and hence is essentially a constant. Use an object for that case.

于 2010-02-12T20:07:11.097 回答