Scala 3中Matchable trait理解困惑及代码报错求助
问题原因与解决方案
你的代码错误出在fold方法的参数使用上:
cellTowers.zip(others)返回的是Seq[(CellTower, CellTower)],每个元素是两个CellTower组成的元组fold的函数参数应该是**(累加器: Boolean, 当前元组: (CellTower, CellTower))**,而你误把第一个参数当成了前一个元组,导致对Boolean类型调用toString,触发Scala 3的类型检查错误(Boolean属于Matchable类型,但你需要返回Boolean)
正确的写法应该是在函数里使用累加器和当前元组,通过逻辑与(&&)保持判断的连续性,同时比较元组里两个CellTower的toString结果:
// CellTower from Google Maps API class unfortunately has no equals() // implementation, but a toString(), so we use this for equality def isEqualTo(cellTowers: Seq[CellTower], others: Seq[CellTower]): Boolean = cellTowers.zip(others).fold(true) { (acc, pair) => acc && pair._1.toString == pair._2.toString }
另外补充两个更简洁的替代方案:
- 使用
forall,更符合语义:
def isEqualTo(cellTowers: Seq[CellTower], others: Seq[CellTower]): Boolean = cellTowers.zip(others).forall { case (ct1, ct2) => ct1.toString == ct2.toString }
- 如果还需要检查两个序列长度是否一致(
zip会截断较长的序列),可以先判断长度:
def isEqualTo(cellTowers: Seq[CellTower], others: Seq[CellTower]): Boolean = cellTowers.length == others.length && cellTowers.zip(others).forall { case (ct1, ct2) => ct1.toString == ct2.toString }
内容的提问来源于stack exchange,提问作者Chris W.
相关产品推荐
相关产品推荐

