|
1 | 1 | package scala.implicits
|
2 | 2 |
|
| 3 | +/** A special class used to implement negation in implicit search. |
| 4 | + * |
| 5 | + * Consider the problem of using implicit `i1` for a query type `D` if an implicit |
| 6 | + * for some other class `C` is available, and using an implicit `i2` if no implicit |
| 7 | + * value of type `C` is available. If we do not want to prioritize `i1` and `i2` by |
| 8 | + * putting them in different traits we can instead define the following: |
| 9 | + * |
| 10 | + * implicit def i1: D(implicit ev: C) = ... |
| 11 | + * implicit def i2: D(implicit ev: Not[C]) = ... |
| 12 | + * |
| 13 | + * `Not` is treated specially in implicit search, similar to the way logical negation |
| 14 | + * is treated in Prolog: The implicit search for `Not[C]` succeeds if and only if the implicit |
| 15 | + * search for `C` fails. |
| 16 | + * |
| 17 | + * In Scala 2 this form of negation can be simulated by setting up a conditional |
| 18 | + * ambiguous implicit and an unconditional fallback, the way it is done with the |
| 19 | + * `default`, `amb1` and `amb2` methods below. Due to the way these two methods are |
| 20 | + * defined, `Not` is also usable from Scala 2. |
| 21 | + * |
| 22 | + * In Dotty, ambiguity is a global error, and therefore cannot be used to implement negation. |
| 23 | + * Instead, `Not` is treated natively in implicit search. |
| 24 | + */ |
3 | 25 | final class Not[+T] private ()
|
4 | 26 |
|
5 |
| -object Not { |
| 27 | +trait LowPriorityNot { |
| 28 | + |
| 29 | + /** A fallback method used to emulate negation in Scala 2 */ |
| 30 | + implicit def default[T]: Not[T] = Not.value |
| 31 | +} |
| 32 | +object Not extends LowPriorityNot { |
| 33 | + |
| 34 | + /** A value of type `Not` to signal a successful search for `Not[C]` (i.e. a failing |
| 35 | + * search for `C`). A reference to this value will be explicitly constructed by Dotty's |
| 36 | + * implicit search algorithm |
| 37 | + */ |
6 | 38 | def value: Not[Nothing] = new Not[Nothing]()
|
| 39 | + |
| 40 | + /** One of two ambiguous methods used to emulate negation in Scala 2 */ |
7 | 41 | implicit def amb1[T](implicit ev: T): Not[T] = ???
|
| 42 | + |
| 43 | + /** One of two ambiguous methods used to emulate negation in Scala 2 */ |
8 | 44 | implicit def amb2[T](implicit ev: T): Not[T] = ???
|
9 | 45 | }
|
0 commit comments