You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/docs/reference/other-new-features/matchable.md
+42Lines changed: 42 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -94,3 +94,45 @@ class Object extends Any, Matchable
94
94
95
95
`Matchable` is currently a marker trait without any methods. Over time
96
96
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
+
classC(valx:String):
106
+
107
+
overridedefequals(that: Any):Boolean=
108
+
that.asInstanceOf[Matchable] match
109
+
casethat: 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
+
opaquetypeMeter=Double
120
+
defMeter(x: Double) = x
121
+
122
+
opaquetypeSecond=Double
123
+
defSecond(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
0 commit comments