Bardzo łatwo jest przypadkowo użyć klasy bez argumentów nieprawidłowo jako wzorca.
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
Zamiast:
scala> (new Foo: Any) match { case _: Foo => true; case _ => false }
res11: Boolean = true
albo lepiej:
scala> case object Bar
defined module Bar
scala> (Bar: Any) match { case Bar => true; case _ => false }
res12: Boolean = true
UPDATE Mam nadzieję, że poniższy zapis pokaże dlaczego pusta lista parametrów korzystne jest brakującej listy parametrów przestarzała.
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()
Obiekt sprawy zazwyczaj będzie nadal preferowany nad pustą listą parametrów.
Zamiast 'case _: Foo' możesz napisać' case Foo() '. – sepp2k
Nadal go nie rozumiem. Dlaczego miałbym oczekiwać, że konstrukt "Bar" utworzy nowe wystąpienie klasy "Bar"? – missingfaktor
** "Bar() // To wywołuje Bar.apply(), ale nie jest symetryczne z definicją klasy." ** - Ten argument odnosi się również do klas normalnych (bezkolizyjnych). Dlaczego więc kompilator nie wyświetla ostrzeżenia po zdefiniowaniu takiej klasy bez listy parametrów? (na przykład 'class Bar') – missingfaktor