如何在Scala中匹配嵌套类?
发布时间:2020-12-16 21:30:48 所属栏目:安全 来源:网络整理
导读:我试过下面的代码(相同的方法写在 Programming in Scala书之后) class Person() { class Room(r: Int,c: Int) { val row = r val col = c override def hashCode: Int = 41 * ( 41 + row.hashCode ) + col.hashCode override def equals(other: Any) = other
我试过下面的代码(相同的方法写在
Programming in Scala书之后)
class Person() { class Room(r: Int,c: Int) { val row = r val col = c override def hashCode: Int = 41 * ( 41 + row.hashCode ) + col.hashCode override def equals(other: Any) = other match { case that: Room => (that canEqual this) && this.row == that.row && this.col == that.col case _ => false } def canEqual(other: Any) = other.isInstanceOf[Room] } val room = new Room(2,1) } val p1 = new Person() val p2 = new Person() println(p1.room == p2.room) >>> false 经过一番分析,我发现Scala重新定义了每个人的实例的课室,这就是两个房间不平等的原因. 解决这个问题的一个可能之处就是将课程放在课外人员中,但这并不总是最简单的. (例如,如果类必须访问Person的某些参数.) 有什么替代方法可以写平等的方法? 解决方法
问题是您的两个房间是路径相关类型的实例:它们的类型是p1.Room和p2.Room:
scala> :type p1.room p1.Room 做这项工作的一种方式是参考房间使用类型选择,即作为人#房. class Person() { class Room(r: Int,c: Int) { val row = r val col = c override def hashCode: Int = // omitted for brevity override def equals(other: Any) = other match { case that: Person#Room => (that canEqual this) && this.row == that.row && this.col == that.col case _ => false } def canEqual(other: Any) = other.isInstanceOf[Person#Room] } val room: Room = new Room(2,1) } val p1 = new Person() val p2 = new Person() scala> p1.room == p2.room res1: Boolean = true (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |