@@ -19,12 +19,18 @@ Those parameters are called _Context Parameters_ because they are inferred by th
19
19
20
20
For instance, consider a program that sorts a list of addresses by two criteria: the city name and then street name.
21
21
22
+ {% tabs contextual_1 %}
23
+ {% tab 'Scala 2 and 3' for=contextual_1 %}
24
+
22
25
``` scala
23
26
val addresses : List [Address ] = ...
24
27
25
28
addresses.sortBy(address => (address.city, address.street))
26
29
```
27
30
31
+ {% endtab %}
32
+ {% endtabs %}
33
+
28
34
The ` sortBy ` method takes a function that returns, for every address, the value to compare it with the other addresses.
29
35
In this case, we pass a function that returns a pair containing the city name and the street name.
30
36
@@ -39,10 +45,25 @@ It is convenient to omit it because we know `String`s are generally compared usi
39
45
40
46
However, it is also possible to pass it explicitly:
41
47
48
+ {% tabs contextual_2 class=tabs-scala-version %}
49
+ {% tab 'Scala 2' for=contextual_2 %}
50
+
51
+ ``` scala
52
+ addresses.sortBy(address => (address.city, address.street))(Ordering .Tuple2 (Ordering .String , Ordering .String ))
53
+ ```
54
+
55
+ {% endtab %}
56
+ {% tab 'Scala 3' for=contextual_2 %}
57
+
42
58
``` scala
43
59
addresses.sortBy(address => (address.city, address.street))(using Ordering .Tuple2 (Ordering .String , Ordering .String ))
44
60
```
45
61
62
+ in Scala 3 ` using ` in an argument list to ` sortBy ` signals passing the context parameter explicitly, avoiding ambiguity.
63
+
64
+ {% endtab %}
65
+ {% endtabs %}
66
+
46
67
In this case, the ` Ordering.Tuple2(Ordering.String, Ordering.String) ` instance is exactly the one that is otherwise inferred by the compiler.
47
68
In other words both examples produce the same program.
48
69
@@ -51,7 +72,5 @@ They help developers write pieces of code that are extensible and concise at the
51
72
52
73
For more details, see the [ Contextual Abstractions chapter] [ contextual ] of this book, and also the [ Reference documentation] [ reference ] .
53
74
54
-
55
-
56
75
[ contextual] : {% link _ overviews/scala3-book/ca-contextual-abstractions-intro.md %}
57
76
[ reference] : {{ site.scala3ref }}/overview.html
0 commit comments