如何在 Scala 中对嵌套类进行模式匹配?
我尝试过下面的代码(相同的方法是在 Programming in Scala book 之后编写的
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
的每个实例重新定义了类 Room
,这就是两个房间不相等的原因。
解决该问题的一种可能性是将类放在 Person
类之外,但这并不总是最简单的。 (例如,如果类必须访问 Person
的某些参数。)
有哪些替代方法可以编写 equal 方法?
I've tried the code below (the equal method is written after Programming in Scala book)
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
After some analysing I found that Scala redefines the class Room
for each instance of Person
and that's the reason the two rooms aren't equal.
One possibility to resolve the problem is to put the class outside of the class Person
, but this isn't always what's easiest. (For example if the class has to access some parameters of Person
.)
What alternatives are there to write the equal method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您的两个房间是路径相关类型的实例:它们的类型是
p1.Room
和p2.Room
:完成这项工作的一种方法是引用使用类型选择到
Room
,即Person#Room
。The problem is that your two rooms are instances of a path-dependent type: their types are
p1.Room
andp2.Room
:One way to make this work is to refer to
Room
using type selection, i.e. asPerson#Room
.