Skip to content

Commit c3f1f34

Browse files
committed
Improve NotGiven example
- Use new Scala 3 syntax uniformly - Don't use a low priority trait since it's a complication not needed for the example
1 parent bec6812 commit c3f1f34

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

docs/docs/reference/contextual/givens.md

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -110,30 +110,23 @@ In each case, a pattern-bound given instance consists of `given` and a type `T`.
110110

111111
Scala 2's somewhat puzzling behavior with respect to ambiguity has been exploited to implement the analogue of a "negated" search in implicit resolution, where a query Q1 fails if some other query Q2 succeeds and Q1 succeeds if Q2 fails. With the new cleaned up behavior these techniques no longer work. But there is now a new special type `scala.util.NotGiven` which implements negation directly.
112112

113-
For any query type Q: NotGiven[Q] succeeds if and only if the implicit search for Q fails. Example:
113+
For any query type `Q`, `NotGiven[Q]` succeeds if and only if the implicit
114+
search for `Q` fails, for example:
114115

115116
```scala
116-
117117
import scala.util.NotGiven
118118

119119
trait Tagged[A]
120120

121121
case class Foo[A](value: Boolean)
122-
trait FooLowPrio {
123-
implicit def fooDefault[A]: Foo[A] = Foo(true)
124-
}
125-
126-
object Foo extends FooLowPrio {
127-
implicit def fooNotTagged[A](implicit ev: NotGiven[Tagged[A]]): Foo[A] = Foo(false)
128-
}
129-
130-
@main def main() =
131-
given Tagged[Int] = null
132-
133-
assert(implicitly[Foo[Int]].value) // fooDefault
134-
135-
assert(!implicitly[Foo[String]].value) // fooNotTagged
136-
122+
object Foo:
123+
given fooTagged[A](using Tagged[A]): Foo[A] = Foo(true)
124+
given fooNotTagged[A](using NotGiven[Tagged[A]]): Foo[A] = Foo(false)
125+
126+
@main def test() =
127+
given Tagged[Int] with {}
128+
assert(implicitly[Foo[Int]].value) // fooTagged is found
129+
assert(!implicitly[Foo[String]].value) // fooNotTagged is found
137130
```
138131

139132
## Given Instance Initialization

0 commit comments

Comments
 (0)