为什么没有参数列表的案例类不推荐使用Scala?为什么编译器会建议使用()
作为参数列表呢?
编辑:
有人请回答我的第二个问题......:
答案 0 :(得分:31)
很容易意外地将无参数案例类错误地用作模式。
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()
案例对象通常仍然优先于空参数列表。
答案 1 :(得分:17)
如果没有参数,case类的每个实例都是无法区分的,因此本质上是一个常量。在这种情况下使用一个对象。