Reputation: 4382
I am trying to compare two Lists containing case classes. Can't figure out which method to override to get this working. Please refer to the code below.
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)
}
}
which returns
false
true
Can't understand why the list comparison returns false. Ultimately what I want is this to be equal
List(DestinationFilter("Amazon"), LocationFilter("Yahoo"), DestinationFilter("Google") == List(DestinationFilter("Yahoo"), LocationFilter("Amazon"), DestinationFilter("Google")
*they should be equal irrespective of order.
Upvotes: 0
Views: 58
Reputation: 13959
You have a typo in your comparison, 11
and 12
should be l1
and l2
:
println(l1 == l2) // true
So 11 == 12
is always false, you're just comparing Int
s.
You also need to change your equals
override, your just comparing key
and value
to themselves, which is always true:
override def equals(that: Any) = {
that match {
case s: SimpleFilter =>
key == s.key && value == s.value //edited
case _ => false
}
}
Upvotes: 1