在Scala 2.9之后,案例类会被删除哪些内容?

时间:2011-05-14 15:16:16

标签: class scala inheritance case deprecated

我知道有关案例类的计划有些变化,例如不允许它们之间的继承:

scala> case class Foo()
defined class Foo

scala> case class Bar() extends Foo()
<console>:9: warning: case class `class Bar' has case ancestor `class Foo'.  Case-to-case inheritance has potentially dangerous bugs which are unlikely to be fixed.  You are strongly encouraged to instead use extractors to pattern match on non-leaf nodes.
       case class Bar() extends Foo()
                  ^
defined class Bar

或没有参数列表的案例类(不确定):

scala> case class Foo
<console>:1: warning: case classes without a parameter list have been deprecated;
use either case objects or case classes with `()' as parameter list.
       case class Foo
                     ^
<console>:7: warning: case classes without a parameter list have been deprecated;
use either case objects or case classes with `()' as parameter list.
       case class Foo
                     ^
defined class Foo

目前还有什么是@deprecated?

1 个答案:

答案 0 :(得分:8)

Scala中的每个类必须至少有一个非隐式参数部分。如果您不包含一个,编译器将为您添加它。

scala> class X
defined class X

scala> new X()
res4: X = X@68003589

scala> class Y
defined class Y

scala> new Y()
res5: Y = Y@467f788b

案例类也不例外。但是与模式匹配的交互是混乱和错误的根源,这促使了弃用。

scala> case class A
<console>:1: warning: case classes without a parameter list have been deprecated;
use either case objects or case classes with `()' as parameter list.
       case class A
                   ^
defined class A

scala> val a = A()
a: A = A()

scala> (a: Any) match { case A => 1; case _ => 2 }
res0: Int = 2

scala> val companion = A
companion: A.type = A

scala> (companion: Any) match { case A => 1; case _ => 2 }
res0: Int = 1

正如迪恩建议的那样,通常情况下最好用案例对象进行建模。

我不知道删除对空-param列表案例类的支持的时间表。在2.9.0中几乎删除了案例类继承,但是这已经推迟到下一个主要版本。

进一步阅读:

Why can't the first parameter list of a class be implicit?