docs.scala-lang
docs.scala-lang copied to clipboard
[Scala 3 book] Section of comparison seems to have an incorrect example
Hello. While taking a look to the documentation on multiversal comparison I saw that it first says:
By default, in Scala 3 you can still create an equality comparison like this:
case class Cat(name: String)
case class Dog(name: String)
val d = Dog("Fido")
val c = Cat("Morris")
d == c // false, but it compiles
But with Scala 3 you can disable such comparisons. By (a) importing scala.language.strictEquality or (b) using the -language:strictEquality compiler flag, this comparison no longer compiles:
import scala.language.strictEquality
val rover = Dog("Rover")
val fido = Dog("Fido")
println(rover == fido) // compiler error
// compiler error message:
// Values of types Dog and Dog cannot be compared with == or !=
I think that the second example tries to create a Dog and a Cat but ends up doing a comparison on two dogs.
Is this the desired example? Because I find it a bit confusing.
If not I can create a quick PR to fix it
It is in fact correct, since Dog and Dog cannot be immediately compared, but need to implement CanEqual as also described here: https://dotty.epfl.ch/docs/reference/contextual/multiversal-equality.html
You can also try it in Scastie:
import scala.language.strictEquality
case class Cat(name: String)
// try commenting the following in to resolve the error
case class Dog(name: String) // derives CanEqual
val d = Dog("Fido")
val c = Cat("Morris")
val rover = Dog("Rover")
val fido = Dog("Fido")
@main def main =
println(rover == fido)
That being said, we are very happy about PRs that explain this more clearly :)