2010-02-12 45 views

回答

31

不小心將一個無參數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 

UPDATE希望下面的記錄將證明爲什麼空參數列表最好將棄用缺少的參數列表。

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 2010-02-13 14:52:34

+0

我還是不明白。爲什麼我會期望'Bar'構造創建一個新類'Bar'的實例? – missingfaktor 2010-02-14 09:49:05

+0

**「Bar()//這會調用Bar.apply(),但不會與類定義對稱。」** - 此參數也適用於普通(非大小寫)類。那麼爲什麼編譯器在我沒有參數列表定義這樣的類時顯示警告? (例如'class Bar') – missingfaktor 2010-02-14 09:51:01

15

沒有參數,case類的每個實例都是難以區分的,因此實質上是一個常量。爲這種情況使用一個對象。

相關問題