在match语句中迭代Map条目

时间:2015-12-19 17:40:41

标签: scala

我正在为Scala类编写equals方法,其中accumUpdates是Map [Long,Any]。 我尝试了以下方法:

  override def equals(other: Any): Boolean = other match {
    case that: DirectTaskResult[_] if (!this.valueBytes.equals(that.valueBytes)) => false
    case that: DirectTaskResult[_] if (this.accumUpdates.size != that.accumUpdates.size) => false
    case that: DirectTaskResult[_] => {
      for ((key, value) <- this.accumUpdates) {
        if (!value.equals(that.accumUpdates.get(key))) false
      }
    }
    case _ => false
  }

上面给了我:

TaskResult.scala:53: type mismatch;
[error]  found   : Unit
[error]  required: Boolean
[error]       for ((key, value) <- this.accumUpdates) {
[error]                         ^
[error] one error found

有人可以提供关于如何迭代Map条目的提示吗?

由于

1 个答案:

答案 0 :(得分:0)

这不是你想做的吗?

case class DirectTaskResult(accumUpdates: Map[Long, Any])

object IterateMap {
  val accumUpdates = Map[Long, Any](1L -> "one", 2L -> 2, 3L -> 3)

  def thirdCaseClauseOfEquals(that: DirectTaskResult) = {
    accumUpdates.keys.forall { key =>
      accumUpdates.get(key) == that.accumUpdates.get(key)
    }
  }
}

这项测试取得了成功:

val t = Map[Long, Any](1L -> "one", 2L -> 2, 3L -> 3)

assert(IterateMap.thirdCaseClauseOfEquals(DirectTaskResult(t)) == true)
assert(IterateMap.thirdCaseClauseOfEquals(DirectTaskResult(t + (4L -> "Four"))) == true)
assert(IterateMap.thirdCaseClauseOfEquals(DirectTaskResult(t - 1L)) == false)