【问题标题】:Scala match class exactly (not extends)Scala 完全匹配类(不扩展)
【发布时间】: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


【解决方案1】:

自动生成的 equals 方法不符合您的建议是有原因的。 canEqual 约定是一种常见且有据可查的约定,因为它允许处理更广泛的常见用例。

在实现 equals 方法时,您并不总是希望排除所有子类,只排除那些覆盖 equals 的子类。如果如您所描述的,有一个 Position3D 类扩展了 Position,并且 Position3D 有一个附加字段 z 是 Position3D equals 方法的一部分,那么 Position3D 当然不应该等于任何正常的 2D 位置。

但是如果出于某种原因用户想要实例化 Position 的匿名子类怎么办?

val pos = new Position(1,2){}

或

trait Foo
val pos = new Position(1,2) with Foo

这个位置可能应该被认为等于new Position(1,2)。在某些情况下,如果混合功能微不足道或仅适用于某些特定的本地范围用例,则不允许这种相等性可能会很乏味。正如其他回复所建议的那样,other.getClass == classOf[Position] 要求客户端 API 混合一个 trait 或出于某种原因创建一个匿名类可能会发现他们正在创建甚至不等于自己的位置。

考虑这段代码:

class Position(val x:Int, val y:Int) {
  override def equals(other:Any) = other match {
    case o:Position if o.getClass==classOf[Position] && o.x==x && o.y==y => true
    case _ => false
  }
}
trait Foo
val p1 = new Position(1,2) with Foo
val p2 = new Position(1,2) with Foo
p1 == p2

结果是false

见: http://www.artima.com/lejava/articles/equality.html

【讨论】:

    【解决方案2】:

    试试:

    other match {
        case that: Position if that.getClass == classOf[Postion] => // or just getClass
            (that canEqual this) &&
                x == that.x &&
                y == that.y
        case: that: Postion => false //this case can be removed
        case _ => false
     }
    

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多