【问题标题】:Which things around case classes will be removed after Scala 2.9 exactly?在 Scala 2.9 之后,案例类的哪些内容将被删除?
【发布时间】:2011-08-25 13:18:25
【问题描述】:

我知道计划对案例类进行一些更改,例如禁止它们之间的继承:

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 还有什么?

【问题讨论】:

  • 没有参数列表的案例类“臭”的原因是因为它们没有从一个实例到另一个实例不同的状态,因为它们没有字段(至少没有通过构造函数设置参数,这是它应该完成的唯一方法......),所以它们应该是真正的案例对象,因为单个实例可以代表所有可能的“状态”。
  • @Dean Wampler:带有空参数列表()的案例类有何不同?
  • 案例类之间的继承为什么臭?

标签: class scala inheritance case deprecated


【解决方案1】:

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

正如 Dean 建议的那样,通常最好使用案例对象对此进行建模。

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

进一步阅读:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多