为什么不带参数列表的case类被弃用了?

42
为什么Scala中不带参数列表的case类被弃用了?而且为什么编译器建议使用()作为参数列表呢?
编辑:有人能回答我的第二个问题吗? :|
2个回答

32

使用不带参数的case class 作为模式时,很容易出错。

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()

相对于一个空参数列表,通常仍然更喜欢使用一个 case 对象。


3
你可以用 case Foo() 替换 case _: Foo - sepp2k
我还是不明白。为什么我会期望“Bar”结构创建类“Bar”的新实例? - missingfaktor
Bar() // 这会调用 Bar.apply(),但与类定义不对称。这个论点也适用于普通(非 case)类。那么为什么当我定义一个没有参数列表的类时(例如 class Bar),编译器不会显示警告呢? - missingfaktor
1
使用new进行普通类实例化时,不需要参数列表。例如:class Bar; new Bar是对称的。Case类会生成一个伴生对象,其中包含apply和unapply方法,因此可以在不使用new的情况下完成构造。 - retronym

21

如果没有参数,每个 case class 实例都是无法区分的,因此实际上是一个常量。 使用对象代替该 case。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接