Scala 迭代match语句中的映射项
我正在为一个Scala类编写equals方法,其中accumUpdates是Map[Long,Any]。 我尝试了以下方法:Scala 迭代match语句中的映射项,scala,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[_]
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
}
override def equals(其他:任意):布尔=其他匹配{
如果(!this.valueBytes.equals(that.valueBytes))=>false
案例为:DirectTaskResult[]if(this.accumUpdates.size!=that.accumUpdates.size)=>false
案例:DirectTaskResult[\u]=>{
for((键,值)false
}
上述情况给了我:
TaskResult.scala:53: type mismatch;
[error] found : Unit
[error] required: Boolean
[error] for ((key, value) <- this.accumUpdates) {
[error] ^
[error] one error found
TaskResult.scala:53:类型不匹配;
[错误]找到:单位
[错误]必需:布尔值
[错误]对于((键,值)请尝试以下操作:
value.filter(value => value._2.equals(value1.get(value._1))).isEmpty
出现错误的原因是,当条件得到满足时,您将返回false,但如果条件的计算结果为true,该怎么办。这不是您想要做的吗
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)
您对映射值的迭代是可以的,但for循环不是。for循环总是返回Unit
。如果您想返回除Unit以外的内容,则必须使用for yield构造。其他答案说明了如何重新格式化它-我特别喜欢使用forAll
的解决方案,它已经内置了for循环
这是收益率和收益率之间差异的说明
scala> def a(mym:Map[_,_]) = {for ((k,v)<-mym) k}
a: (mym: Map[_, _])Unit
scala> def a(mym:Map[_,_]) = {for ((k,v)<-mym) yield k}
a: (mym: Map[_, _])scala.collection.immutable.Iterable[Any]
scala>defa(mym:Map[u,v])={for((k,v)defa(mym:Map[u,v])={for((k,v)