类列表的平等性

时间:2015-06-29 14:14:08

标签: scala

我正在尝试比较包含案例类的两个列表。无法确定要覆盖哪种方法才能使其正常工作。请参考下面的代码。

servers.conf

返回

trait Filter {
  def toQueryString: String
}
trait SimpleFilter extends Filter {
  val key: String
  val value: Any

  override def toQueryString = value match {
    case v: String => s"$key='$v'"
    case _         => s"$key=$value"
  }
  override def toString = "$key:$value"

  override def equals(that: Any) = {
    that match {
      case s: SimpleFilter => {
        key == key && value == value
      }
      case _ => false
    }
  }
  override def hashCode() = key.hashCode + value.hashCode
}

class DestinationFilter(override val value: String) extends SimpleFilter {
  override val key = "destination"
}
object DestinationFilter {
  def apply(value: String) = new DestinationFilter(value)
}

object Tester {

  def main(args: Array[String]): Unit = {
    val d1 = DestinationFilter("Google")
    val d2 = DestinationFilter("Google")
    val l1 = List(d1)
    val l2 = List(d2)
    println(11 == 12)
    println(d1 == d2)
  }

}

无法理解为什么列表比较返回false。最终我想要的是这是平等的

false
true

*无论顺序如何,它们都应该相等。

1 个答案:

答案 0 :(得分:1)

您的比较中有一个拼写错误,1112应为l1l2

println(l1 == l2) // true

所以11 == 12总是假的,你只是比较Int

您还需要更改equals覆盖,只需将keyvalue与自己进行比较,这始终是正确的:

  override def equals(that: Any) = {
      that match {
        case s: SimpleFilter =>
          key == s.key && value == s.value //edited
        case _ => false
      }
    }