【发布时间】:2014-05-07 16:03:22
【问题描述】:
问题
在 Scala 中,有没有办法编写一个 match 子句来匹配对象的类,但不匹配任何扩展类?
动机
这可能看起来很迂腐……确实如此。
反正看到IntelliJ生成的equals函数就想到了:
class Position(val x: Float, val y: Float) {
def canEqual(other: Any): Boolean = other.isInstanceOf[Position]
override def equals(other: Any): Boolean = other match {
case that: Position =>
(that canEqual this) &&
x == that.x &&
y == that.y
case _ => false
}
// generated hashCode omitted for brevity
}
这里我们可以看到other 被类匹配为Position,然后canEqual 用于设置匹配的上限。也就是说,other 仍然可以是 Position3D,即使 x 和 y 坐标相同,它也不应该等于 Position。
这是有道理的,但我想知道某种形式的 Scala 魔法是否会让我们明确匹配 Position 类而不是子类。
【问题讨论】:
-
这很简单:将 Position 类设为 final 并将 Position3D 设为独立类。
-
我不想让继承成为不可能。我只想明确地
match类,而不是任何扩展类。
标签: scala match equals matching