为什么不使用Scala弃用没有参数列表的案例类?为什么编译器建议改用()
作为参数列表?
编辑:
有人请回答我的第二个问题...:|
最佳答案
意外地将no-arg 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()
通常情况下,与空参数列表相比,case对象仍然是首选。
关于scala - 为什么不推荐没有参数列表的案例类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2254710/