Skip to content

[Scala 3 book] Section of comparison seems to have an incorrect example #1905

Open
@Guisanpea

Description

@Guisanpea

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

Activity

changed the title [-]Section of comparison seems to have an incorrect example[/-] [+][Scala 3 book] Section of comparison seems to have an incorrect example[/+] on Jan 21, 2021
b-studios

b-studios commented on Feb 5, 2021

@b-studios
Contributor

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 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

scala-3scala 3 documentation

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

    Development

    No branches or pull requests

      Participants

      @b-studios@Guisanpea

      Issue actions

        [Scala 3 book] Section of comparison seems to have an incorrect example · Issue #1905 · scala/docs.scala-lang