40
A
回答
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對象通常仍然會優先於空的參數列表。
15
沒有參數,case類的每個實例都是難以區分的,因此實質上是一個常量。爲這種情況使用一個對象。
相關問題
- 1. 推薦的註冊表使用情況
- 2. 爲什麼Logger.isInfoEnabled不推薦使用org.jboss.logging.Logger?
- 3. 爲什麼不推薦使用isJavaLetterOrDigit?
- 4. 爲什麼不推薦使用JButton.enable?
- 5. 爲什麼不推薦使用struts2 FilterDispatcher?
- 6. 爲什麼SET不推薦使用?
- 7. 爲什麼不推薦使用StringTokenizer?
- 8. std :: iterator爲什麼不推薦使用?
- 9. Object.observe()爲什麼不推薦使用
- 10. 爲什麼不推薦使用std :: strstream?
- 11. 爲什麼不推薦使用body.scrollTop?
- 12. 爲什麼不推薦使用window.showModalDialog?代替使用什麼?
- 13. 爲什麼不推薦使用assert_template,而應該使用什麼?
- 14. 爲什麼在這種情況下使用Math.max作爲參數不起作用?
- 15. Apple推薦用於RAM使用情況?
- 16. jQuery切換不推薦使用什麼?
- 17. 爲什麼不推薦使用包org.apache.hadoop.mapred中的大多數類?
- 18. 默認情況下爲什麼不應用(RankNTypes使用)?
- 19. C++:爲什麼「使用」在某些情況下不起作用?
- 20. 爲什麼不推薦HibernateTemplate?
- 21. 如何找出iOS中爲什麼不推薦使用函數?
- 22. 由什麼來取代在nextgen下不推薦使用的TSysCharSet?
- 23. perl中的錯誤:不推薦使用散列作爲參考
- 24. PHP對不推薦使用的函數有什麼作用?
- 25. 爲什麼在這種情況下不能使用try-with-resource?
- 26. (爲什麼)在這種情況下MySQL不能使用索引?
- 27. 爲什麼不能在這種情況下使用隱式?
- 28. 爲什麼不推薦使用hibernate的ClassMetadata.getIdentifier(Object,EntityMode)
- 29. 爲什麼不推薦使用來自JUnit 4的assertEquals(Object [],Object [])?
- 30. Spring安全中的接口WebSecurityExpressionHandler爲什麼不推薦使用?
代替'case _:Foo',你可以寫'case Foo()'。 – sepp2k 2010-02-13 14:52:34
我還是不明白。爲什麼我會期望'Bar'構造創建一個新類'Bar'的實例? – missingfaktor 2010-02-14 09:49:05
**「Bar()//這會調用Bar.apply(),但不會與類定義對稱。」** - 此參數也適用於普通(非大小寫)類。那麼爲什麼編譯器在我沒有參數列表定義這樣的類時顯示警告? (例如'class Bar') – missingfaktor 2010-02-14 09:51:01