Skip to content

Commit 625f754

Browse files
committed
Add section on Matchable and Universal Equality
1 parent 0c772e2 commit 625f754

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

docs/docs/reference/other-new-features/matchable.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,45 @@ class Object extends Any, Matchable
9494

9595
`Matchable` is currently a marker trait without any methods. Over time
9696
we might migrate methods `getClass` and `isInstanceOf` to it, since these are closely related to pattern-matching.
97+
98+
### `Matchable` and Universal Equality
99+
100+
Methods that pattern-match on selectors of type `Any` will need a cast once the
101+
Matchable warning is turned on. The most common such method is the universal
102+
`equals` method. It will have to be written as in the following example:
103+
104+
```scala
105+
class C(val x: String):
106+
107+
override def equals(that: Any): Boolean =
108+
that.asInstanceOf[Matchable] match
109+
case that: C => this.x == that.x
110+
case _ => false
111+
```
112+
The cast of `that` to `Matchable` serves as an indication that universal equality
113+
is unsafe in the presence of abstract types and opaque types since it cannot properly distinguish the meaning of a type from its representation. The cast
114+
is guaranteed to succeed at run-time since `Any` and `Matchable` both erase to
115+
`Object`.
116+
117+
For instance, consider the definitions
118+
```scala
119+
opaque type Meter = Double
120+
def Meter(x: Double) = x
121+
122+
opaque type Second = Double
123+
def Second(x: Double) = x
124+
```
125+
Here, universal `equals` will return true for
126+
```scala
127+
Meter(10).equals(Second(10))
128+
```
129+
even though this is clearly false mathematically. With [multiversal equality](../contextual/multiversal-equality.html) one can mitigate that problem somewhat by turning
130+
```scala
131+
Meter(10) == Second(10)
132+
```
133+
into a type error.
134+
135+
136+
137+
138+

0 commit comments

Comments
 (0)