本文介绍了为什么不推荐没有参数列表的案例类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

为什么不带参数列表的案例类在Scala中被弃用?为什么编译器建议使用()作为参数列表?

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

编辑:

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

Someone please answer my second question... :|

推荐答案

很容易意外地将no-arg case类错误地用作模式。

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

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

UPDATE 下面的文字记录将说明为什么不推荐使用空参数列表而不是不推荐使用的缺失参数列表。

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

与空参数列表相比,通常还是首选使用case对象。

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

这篇关于为什么不推荐没有参数列表的案例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 02:12