From 68426507b2870e92235ec9903fba9743f56e4d22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Brachth=C3=A4user?= Date: Fri, 5 Feb 2021 15:29:55 +0100 Subject: [PATCH 1/2] Add an explanation about using opaque types on classes --- .../reference/other-new-features/opaques.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/docs/docs/reference/other-new-features/opaques.md b/docs/docs/reference/other-new-features/opaques.md index 5bed38293b21..dfb94b1f222e 100644 --- a/docs/docs/reference/other-new-features/opaques.md +++ b/docs/docs/reference/other-new-features/opaques.md @@ -133,4 +133,34 @@ end User On the other hand, the call `roItem.rights.isOneOf(ReadWrite)` would give a type error since `Permissions` and `PermissionChoice` are different, unrelated types outside `Access`. + +### Opaque Type Members on Classes +While typically, opaque types are used toghether with objects to hide implementation details of a module, they can also be used with classes. + +For example, we can redefine the above example of Logarithms as a class. +```scala +class Logarithms: + + opaque type Logarithm = Double + + def apply(d: Double): Logarithm = math.log(d) + + def safe(d: Double): Option[Logarithm] = + if d > 0.0 then Some(math.log(d)) else None + + def mul(x: Logarithm, y: Logarithm) = x + y +``` + +Opaque type members of different instances are treated as different: +```scala +val l1 = new Logarithms +val l2 = new Logarithms +val x = l1(1.5) +val y = l1(2.6) +val z = l2(3.1) +l1.mul(x, y) // type checks +l1.mul(x, z) // error: found l2.Logarithm, required l1.Logarithm +``` +In general, one can think of an opaque type as being only transparent in the scope of `private[this]`. + [More details](opaques-details.md) From c7ad88456e357b36a60428d1f46297afff8130f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20Brachth=C3=A4user?= Date: Fri, 5 Feb 2021 16:36:37 +0100 Subject: [PATCH 2/2] Fix typo --- docs/docs/reference/other-new-features/opaques.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference/other-new-features/opaques.md b/docs/docs/reference/other-new-features/opaques.md index dfb94b1f222e..ea51b44baed0 100644 --- a/docs/docs/reference/other-new-features/opaques.md +++ b/docs/docs/reference/other-new-features/opaques.md @@ -135,7 +135,7 @@ since `Permissions` and `PermissionChoice` are different, unrelated types outsid ### Opaque Type Members on Classes -While typically, opaque types are used toghether with objects to hide implementation details of a module, they can also be used with classes. +While typically, opaque types are used together with objects to hide implementation details of a module, they can also be used with classes. For example, we can redefine the above example of Logarithms as a class. ```scala