Skip to content

Commit 49c59f5

Browse files
authored
Merge pull request #11328 from dotty-staging/docs/opaques-on-classes
Add an explanation about using opaque types on classes
2 parents eb71997 + c7ad884 commit 49c59f5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,34 @@ end User
133133
On the other hand, the call `roItem.rights.isOneOf(ReadWrite)` would give a type error
134134
since `Permissions` and `PermissionChoice` are different, unrelated types outside `Access`.
135135

136+
137+
### Opaque Type Members on Classes
138+
While typically, opaque types are used together with objects to hide implementation details of a module, they can also be used with classes.
139+
140+
For example, we can redefine the above example of Logarithms as a class.
141+
```scala
142+
class Logarithms:
143+
144+
opaque type Logarithm = Double
145+
146+
def apply(d: Double): Logarithm = math.log(d)
147+
148+
def safe(d: Double): Option[Logarithm] =
149+
if d > 0.0 then Some(math.log(d)) else None
150+
151+
def mul(x: Logarithm, y: Logarithm) = x + y
152+
```
153+
154+
Opaque type members of different instances are treated as different:
155+
```scala
156+
val l1 = new Logarithms
157+
val l2 = new Logarithms
158+
val x = l1(1.5)
159+
val y = l1(2.6)
160+
val z = l2(3.1)
161+
l1.mul(x, y) // type checks
162+
l1.mul(x, z) // error: found l2.Logarithm, required l1.Logarithm
163+
```
164+
In general, one can think of an opaque type as being only transparent in the scope of `private[this]`.
165+
136166
[More details](opaques-details.md)

0 commit comments

Comments
 (0)