Skip to content

Commit

Permalink
Add CanEqual instance for Map (#15886)
Browse files Browse the repository at this point in the history
Fixes #15849
  • Loading branch information
smarter authored Dec 19, 2022
2 parents f3f8ae6 + 27f6cac commit ddc96b9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
8 changes: 6 additions & 2 deletions library/src/scala/CanEqual.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package scala

import annotation.implicitNotFound
import scala.collection.{Seq, Set}
import scala.collection.{Seq, Set, Map}

/** A marker trait indicating that values of type `L` can be compared to values of type `R`. */
@implicitNotFound("Values of types ${L} and ${R} cannot be compared with == or !=")
Expand All @@ -26,14 +26,18 @@ object CanEqual {
given canEqualNumber: CanEqual[Number, Number] = derived
given canEqualString: CanEqual[String, String] = derived

// The next 6 definitions can go into the companion objects of their corresponding
// The following definitions can go into the companion objects of their corresponding
// classes. For now they are here in order not to have to touch the
// source code of these classes
given canEqualSeqs[T, U](using eq: CanEqual[T, U]): CanEqual[Seq[T], Seq[U]] = derived
given canEqualSeq[T](using eq: CanEqual[T, T]): CanEqual[Seq[T], Seq[T]] = derived // for `case Nil` in pattern matching

given canEqualSet[T, U](using eq: CanEqual[T, U]): CanEqual[Set[T], Set[U]] = derived

given canEqualMap[K1, V1, K2, V2](
using eqK: CanEqual[K1, K2], eqV: CanEqual[V1, V2]
): CanEqual[Map[K1, V1], Map[K2, V2]] = derived

given canEqualOptions[T, U](using eq: CanEqual[T, U]): CanEqual[Option[T], Option[U]] = derived
given canEqualOption[T](using eq: CanEqual[T, T]): CanEqual[Option[T], Option[T]] = derived // for `case None` in pattern matching

Expand Down
5 changes: 5 additions & 0 deletions tests/neg/equality1.scala
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,9 @@ object equality1 {
println("empty")
}

Map("k1" -> 1) == Map("k2" -> 2, "k3" -> 3)
Map(Color.Red -> Status.Inactive) == Map(Color.Green -> Status.Active(5))

Map("k1" -> 5) == Map('k' -> 5) // error
Map("k1" -> new A) == Map("k2" -> new B) // error
}

0 comments on commit ddc96b9

Please sign in to comment.