为什么Scala中不带参数列表的case类被弃用了?而且为什么编译器建议使用
编辑:有人能回答我的第二个问题吗? :|
()
作为参数列表呢?编辑:有人能回答我的第二个问题吗? :|
()
作为参数列表呢?使用不带参数的case class 作为模式时,很容易出错。
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 对象。
如果没有参数,每个 case class 实例都是无法区分的,因此实际上是一个常量。 使用对象代替该 case。
case Foo()
替换case _: Foo
。 - sepp2kclass Bar
),编译器不会显示警告呢? - missingfaktornew
进行普通类实例化时,不需要参数列表。例如:class Bar; new Bar
是对称的。Case类会生成一个伴生对象,其中包含apply和unapply方法,因此可以在不使用new
的情况下完成构造。 - retronym