Skip to content

How to handle overriden equals with Matchable? #10855

Closed
@joschua-fink

Description

@joschua-fink

Minimized example

When overriding the equals method, this is a common pattern in Scala 2:

trait Foo {
  override def equals(obj: Any): Boolean = obj match {
    case foo: Foo =>
      ???
    case _ =>
      false
  }
}

Output

Using Scala 3.0.0-M3 with -source 3.1 I get the following warning:

[warn] 14 |      case foo: Foo =>
[warn]    |                ^^^
[warn]    |                pattern selector should be an instance of Matchable,
[warn]    |                but it has unmatchable type Any instead

Question

What is the alternative for this pattern? Since according to the documentation isInstanceOf may also be moved into Matchable, which will make the following workaround (which is basically the way it's done in Java) inviable as well:

trait Bar {
  override def equals(obj: Any): Boolean = {
    if obj.isInstanceOf[Bar] then
      val bar = obj.asInstanceOf[Bar]
      ???
    else
      false
  }
}

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions