Skip to content

Commit 1c25381

Browse files
committed
Update #class-context-parameters in using-clauses.md
1 parent 1d0a458 commit 1c25381

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

docs/_docs/reference/contextual/using-clauses.md

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -50,29 +50,36 @@ Generally, context parameters may be defined either as a full parameter list `(p
5050

5151
## Class Context Parameters
5252

53-
If a class context parameter is made a member by adding a `val` or `var` modifier,
54-
then that member is available as a given instance.
53+
To make a class context parameter visible from outside the class body, it can be made into a member by adding a `val` or `var` modifier.
54+
```scala
55+
class GivenIntBox(using val usingParameter: Int):
56+
def myInt = summon[Int]
5557

56-
Compare the following examples, where the attempt to supply an explicit `given` member induces an ambiguity:
58+
val b = GivenIntBox(using 23)
59+
import b.usingParameter
60+
summon[Int] // 23
61+
```
5762

63+
This is preferable to creating an explicit `given` member, as the latter creates ambiguity inside the class body:
5864
```scala
59-
class GivenIntBox(using val givenInt: Int):
60-
def n = summon[Int]
61-
62-
class GivenIntBox2(using givenInt: Int):
63-
given Int = givenInt
64-
//def n = summon[Int] // ambiguous
65+
class GivenIntBox2(using usingParameter: Int):
66+
given givenMember: Int = usingParameter
67+
def n = summon[Int] // ambiguous given instances: both usingParameter and givenMember match type Int
6568
```
6669

67-
The `given` member is importable as explained in the section on [importing `given`s](./given-imports.md):
70+
From the outside of `GivenIntBox`, `usingParameter` appears as if it were defined in the class as `given usingParameter: Int`, in particular it must be imported as described in the section on [importing `given`s](./given-imports.md).
6871

6972
```scala
7073
val b = GivenIntBox(using 23)
74+
// Works:
7175
import b.given
7276
summon[Int] // 23
77+
usingParameter // 23
7378

79+
// Fails:
7480
import b.*
75-
//givenInt // Not found
81+
summon[Int] // No given instance found
82+
usingParameter // Not found
7683
```
7784

7885
## Inferring Complex Arguments

0 commit comments

Comments
 (0)