Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

scala - Why were the case classes without a parameter list deprecated?

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

EDIT :

Someone please answer my second question... :|

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Instead of:

scala> (new Foo: Any) match { case _: Foo => true; case _ => false } 
res11: Boolean = true

Or better:

scala> case object Bar                                               
defined module Bar

scala> (Bar: Any) match { case Bar => true; case _ => false }        
res12: Boolean = true

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...