scala 为什么不推荐使用没有参数列表的案例类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2254710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:56:28  来源:igfitidea点击:

Why were the case classes without a parameter list deprecated?

scaladeprecatedcase-class

提问by missingfaktor

Why were the case classes without a parameter list deprecated from Scala? And why does compiler suggest to use ()as parameter list instead?

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

EDIT :

编辑 :

Someone please answer my second question... :|

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

采纳答案by retronym

It is really easy to accidentally use a no-arg case class incorrectly as a pattern.

不小心将 no-arg case 类错误地用作模式真的很容易。

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

Instead of:

代替:

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

Or better:

或更好:

scala> case object Bar                                               
defined module Bar

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

UPDATEHopefully the transcript below will demonstrate why an empty parameter list is preferred to the deprecated missing parameter list.

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

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

A case object would usually still be preferred over an empty parameter list.

与空参数列表相比,case 对象通常仍然是首选。

回答by Randall Schulz

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

如果没有参数,case 类的每个实例都是不可区分的,因此本质上是一个常量。在这种情况下使用一个对象。