Scala 禁止case class inheritance

case class Person(name: String, age: Int)
case class FootballPlayer(name: String, age: Int, number: Int) extends Person(name, age)

在编译时会报出以下错误:

Error:(5, 12) case class FootballPlayer has case ancestor Person, but case-to-case inheritance is prohibited. To overcome this limitation, use extractors to pattern match on non-leaf nodes.
case class FootballPlayer(name: String, age: Int, number: Int) extends Person(name, age)
^

原因有挺多,下边的两篇文章讲了下理由,但我还是没明白其中的必要性。

http://tech.schmitztech.com/scala/caseclassinheritence.html

http://stackoverflow.com/questions/11158929/what-is-so-wrong-with-case-class-inheritance


我们可以使得两个case class继承同一个trait来实际于case class继承的行为,但是这样就得自己写extractor了。比如

  sealed trait Person{
def age: Int
def name: String
}
case class FootballPlayer(name: String, age: Int, number: Int) extends Person
val torres = FootballPlayer("Fernando Torres", 31, 19)
val Person(name, age) = torres // can't resolve symbal Person

会编译出错, 因为Person是个trait,它并不支持extractor的语法。

需要给Person加个Companion object,像这样

  object Person{
def unapply(p: Person) = Some((p.name, p.age))
}

这时就能用extractor了

  val torres = FootballPlayer("Fernando Torres", 31, 19)
val Person(name, age) = torres

编译器会为case class生成equals方法,但普通类就不会了。

  sealed trait Person{
def age: Int
def name: String
} case class FootballPlayer(name: String, age: Int, number: Int) extends Person
class Doctor(val name: String, val age: Int) extends Person
val torresA = FootballPlayer("Fernando Torres", 31, 19)
val torresB = FootballPlayer("Fernando Torres", 31, 19)
println(torresA == torresB)//true val docA = new Doctor("C", 30)
val docB = new Doctor("C", 30)
println(docA == docB)//false

这时,当两个FootballPlayer的构造参数相同,它们就相等。但是对于Doctor类来说不是这样了。

当给FootballPlayer这个case class的父类Person定义了equals方法之后,就不是这样了。

 sealed trait Person{self =>
def age: Int
def name: String
override def equals(that: Any):Boolean = {
that match{
case p: Person => p.age == self.age && p.name == self.name
case _ => false
}
}
override def hashCode: Int = {
var hash = 1
hash = hash * 31 + age
hash = hash * 31 + {if(name !=null) name.hashCode else 0}
hash
}
}
case class FootballPlayer(name: String, age: Int, number: Int) extends Person
class Doctor(val name: String, val age: Int) extends Person
val torresA = FootballPlayer("Fernando Torres", 31, 19)
val torresB = FootballPlayer("Fernando Torres", 31, 19)
torresA.equals(torresB)
println(torresA == torresB)//true val docA = new Doctor("C", 30)
val docB = new Doctor("C", 30)
println(docA == docB) //true val footballPlayerC = FootballPlayer("C", 30, 30)
println(footballPlayerC == docA) //true
println(footballPlayerC.hashCode())//
println(docA.hashCode())//

貌似这时候case class就不会生成equals方法了, 转而使用父类Person的equals方法。并且要记得同时在Person中覆盖hashCode方法,不然就破坏了equals对hashCode的要求。

case class inheritance的更多相关文章

  1. Three Sources of a Solid Object-Oriented Design

    pingback :http://java.sys-con.com/node/84633?page=0,1 Object-oriented design is like an alloy consis ...

  2. C#调用C++导出类(转)

    由于使用别人的Dll,导出的是一个实体类,在C#里封送很难,百度下,有个朋友回复一篇英文的,虽然不一定使用,但可以作为一个知识点,现把原文贴下: c#调用C++写的dll导出类,包含继承,重载等详细介 ...

  3. TFS 2015 Build Agent failing syncing the repository 获取源码 不全 失败

    当我们使用TFS2015d的生成代理时,我们将生成定义加入代理池队列中,但是代理可能无法完全下载我们在TFS代码浏览器中看到的所有目录,这肯定会导致编译失败呀!为什么呢? 原因在于tfscompile ...

  4. Ubuntu+apache安装redmin

    公司要迁移redmin,本来以为是一个很简单的项目,想不到整整搞了一天加一个晚上. 首先是对ruby的安装不熟悉,现在明白了ruby的安装顺序是先安装rvm版本管理,然后用rvm安装ruby,安装好后 ...

  5. The IDL compiler

    The IDL compiler or bindings generator transcompiles Web IDL to C++ code, specifically bindings betw ...

  6. C++: virtual inheritance and Cross Delegation

    Link1: Give an example Note: I think the Storable::Write method should also be pure virtual. http:// ...

  7. JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance

    // the parent constructor function Parent(name) { this.name = name || 'Adam'; } // adding functional ...

  8. Effective Java 17 Design and document for inheritance or else prohibit it

    Principles The class must document its self-use of overridable methods. A class may have to provide ...

  9. Think Python - Chapter 18 - Inheritance

    In this chapter I present classes to represent playing cards, decks of cards, and poker hands.If you ...

随机推荐

  1. svn 分支整个项目合并主干

    1.首先主干要更新最新版本. 2.找到主干(trunk)点击右键--合并--合并类型选择(合并一个版本范围)点击下一步--合并源选择整个分支项目--将要合并的修改版本范围(选择指定(a)范围)点击下一 ...

  2. win7下的mstsc ubuntu下的rdesktop

    远程图形化登录, win7下: 开始->mstsc->10.108.103.93即可进行后续输入账号密码验证登录. 功能类似rdesktop. 如图:

  3. 详解在Visual Studio中使用git版本系统

    转自:http://www.uml.org.cn/pzgl/201206211.asp

  4. spring aop配置及用例说明(2)

    欢迎交流转载:http://www.cnblogs.com/shizhongtao/p/3473362.html 这里先介绍下几个annotation的含义, @Before:表示在切入点之前执行. ...

  5. 安装MySQL总结

    由于MySQL的版本不同,所以会有不同的安装方式.在下以Linux系统下MySQL5.1.19版本为例,进行安装,初学还望指正. 一.安装编译软件(简单的yum安装) gcc gcc-c++ ncur ...

  6. Hadoop fs命令详解

    本文非原创,转载自http://www.superwu.cn/2013/07/31/312 另外参考:http://www.blogjava.net/changedi/archive/2013/08/ ...

  7. String inputStream file转化

    String --> InputStreamByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes()); Inp ...

  8. python(六)面向对象

    1.封装 支持多重继承,但如果不需要的时候最好不要使用,避免出现不必要的bug: 2.继承 3.多态 4.构造函数 5.私有和共有 在属性前写两个下滑线定义就是私有的

  9. SQL Server 2008 R2密钥序列号

    SQL Server 2008 R2密钥序列号 序列号: 开发版(Developer): PTTFM-X467G-P7RH2-3Q6CG-4DMYB 企业版(Enterprise): JD8Y6-HQ ...

  10. uniquery 配合 mssql 自带存储过程实现分页

    --使用系统存储过程实现的通用分页存储过程 -- 此过程原作者,应该是:邹健老前辈 CREATE PROC sp_PageView @sql ntext, --要执行的sql语句 , --要显示的页码 ...