You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
description: This page demonstrates how to use 'given' instances and 'using' clauses in Scala 3.
5
5
num: 59
@@ -12,16 +12,24 @@ layout: multipage-overview
12
12
permalink: "/zh-cn/scala3/book/:title.html"
13
13
---
14
14
15
-
Scala 3 offers two important feature for contextual abstraction:
16
15
17
-
-**Using Clauses** allow you to specify parameters that, at the call site, can be omitted by the programmer and should be automatically provided by the context.
18
-
-**Given Instances** let you define terms that can be used by the Scala compiler to fill in the missing arguments.
Let us assume that the configuration does not change throughout most of our code base.
37
-
Passing `c` to each and every method call (like `renderWidget`) becomes very tedious and makes our program more difficult to read, since we need to ignore the `c` argument.
38
44
39
-
#### Using `using` to mark parameters as contextual
40
-
In Scala 3, we can mark some of the parameters of our methods as _contextual_.
By starting a parameter section with the keyword `using`, we tell the Scala compiler that at the callsite it should automatically find an argument with the correct type.
50
-
The Scala compiler thus performs **term inference**.
51
66
52
-
In our call to `renderWidget(List("cart"))` the Scala compiler will see that there is a term of type `Config` in scope (the `c`) and automatically provide it to `renderWidget`.
Explicitly providing contextual parameters can be useful if we have multiple different values in scope that would make sense and we want to make sure that the correct one is passed to the function.
74
104
75
-
For all other cases, as we will see in the next Section, there is also another way to bring contextual values into scope.
We have seen that we can explicitly pass arguments as contextual parameters by marking the argument section of the _call_ with `using`.
79
-
However, if there is _a single canonical value_ for a particular type, there is another preferred way to make it available to the Scala compiler: by marking it as `given`.
// this is the value the Scala compiler will infer
89
128
// as argument to contextual parameters of type Config
90
129
```
91
-
In the above example we specify that whenever a contextual parameter of type `Config` is omitted in the current scope, the compiler should infer `config` as an argument.
92
130
93
-
Having defined a given for `Config`, we can simply call `renderWebsite`:
0 commit comments