Implement custom class with overriding hashCode
and equals
methods.
case class Value(x: Int) {
override def hashCode = {
println(s"hashCode: $x")
x
}
override def equals(other: Any) = {
println(s"equals: $this == $other??")
other match {
case v: Value => v.x == this.x
case _ => false
}
}
}
First, Seq#map
.
scala> val result = (1 to 5).toSeq.map { Value.apply } .map { v => Value(v.x % 2) }
result: scala.collection.immutable.IndexedSeq[Value] = Vector(Value(1), Value(0), Value(1), Value(0), Value(1))
Second, Set#map
.
scala> val result = (1 to 5).toSet.map { Value.apply } .map { v => Value(v.x % 2) }
hashCode: 5
hashCode: 1
hashCode: 2
hashCode: 3
hashCode: 4
hashCode: 1
hashCode: 1
equals: Value(1) == Value(1)??
hashCode: 0
hashCode: 1
equals: Value(1) == Value(1)??
hashCode: 0
equals: Value(0) == Value(0)??
result: scala.collection.immutable.Set[Value] = Set(Value(0), Value(1))
Executing Set#map
also hashCode
and equals
are invoked to stay as a Set
instance.