Skip to content

Commit

Permalink
Add CanEqual instance for Seq to match Nil case
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-lee committed Aug 21, 2021
1 parent 68044a6 commit 32a99fd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
6 changes: 4 additions & 2 deletions library/src/scala/CanEqual.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ object CanEqual {
given canEqualNumber: CanEqual[Number, Number] = derived
given canEqualString: CanEqual[String, String] = derived

// The next five definitions can go into the companion objects of their corresponding
// The next 6 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 canEqualSeq[T, U](using eq: CanEqual[T, U]): CanEqual[Seq[T], Seq[U]] = derived
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 canEqualOptions[T, U](using eq: CanEqual[T, U]): CanEqual[Option[T], Option[U]] = derived
Expand Down
2 changes: 1 addition & 1 deletion tests/neg/derive-eq.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ object Test extends App {
val y: Triple[List[Two], One, Two] = ???
val z: Triple[One, List[Two], One] = ???
x == y // OK
y == x // OK
x == x // OK
y == y // OK

y == x // error
x == z // error
z == y // error
}
15 changes: 15 additions & 0 deletions tests/neg/equality1.scala
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,19 @@ object equality1 {
(1, "a") == (1, "a", true) // error: cannot compare
(1, "a", true, 't', 10L) == (1, "a", 1.5D, 't', 10L) // error: cannot compare


val ns1 = List(1, 2, 3, 4, 5)
val ns2 = List(1, 2, 3, 4, 5)
ns1 == ns2

val ss = List("1", "2", "3", "4", "5")
ns1 == ss // error: cannot compare

ns1 match {
case n :: ns =>
println(s"head: $n, tail: ${ns.mkString("[", ",", "]")}")
case Nil =>
println("empty")
}

}

0 comments on commit 32a99fd

Please sign in to comment.