41

パラメータリストのないケースクラスがScalaから非推奨になったのはなぜですか?そして、なぜコンパイラは()代わりにパラメータリストとして使用することを提案するのですか?

編集 :

誰かが私の2番目の質問に答えてください...:|

4

2 に答える 2

32

誤って引数なしの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

それ以外の:

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

パラメータがないと、caseクラスのすべてのインスタンスは区別がつかないため、本質的に定数になります。その場合はオブジェクトを使用してください。

于 2010-02-12T20:07:11.097 に答える