Skip to content

Commit f3464af

Browse files
authored
Merge pull request #2587 from benluo/_overview/scala3-book/num14-code-tabs
add code tabs in num14.
2 parents a5374ef + f967ea7 commit f3464af

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

_overviews/scala3-book/taste-contextual-abstractions.md

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,18 @@ Those parameters are called _Context Parameters_ because they are inferred by th
1919

2020
For instance, consider a program that sorts a list of addresses by two criteria: the city name and then street name.
2121

22+
{% tabs contextual_1 %}
23+
{% tab 'Scala 2 and 3' for=contextual_1 %}
24+
2225
```scala
2326
val addresses: List[Address] = ...
2427

2528
addresses.sortBy(address => (address.city, address.street))
2629
```
2730

31+
{% endtab %}
32+
{% endtabs %}
33+
2834
The `sortBy` method takes a function that returns, for every address, the value to compare it with the other addresses.
2935
In this case, we pass a function that returns a pair containing the city name and the street name.
3036

@@ -39,10 +45,25 @@ It is convenient to omit it because we know `String`s are generally compared usi
3945

4046
However, it is also possible to pass it explicitly:
4147

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+
4258
```scala
4359
addresses.sortBy(address => (address.city, address.street))(using Ordering.Tuple2(Ordering.String, Ordering.String))
4460
```
4561

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+
4667
In this case, the `Ordering.Tuple2(Ordering.String, Ordering.String)` instance is exactly the one that is otherwise inferred by the compiler.
4768
In other words both examples produce the same program.
4869

@@ -51,7 +72,5 @@ They help developers write pieces of code that are extensible and concise at the
5172

5273
For more details, see the [Contextual Abstractions chapter][contextual] of this book, and also the [Reference documentation][reference].
5374

54-
55-
5675
[contextual]: {% link _overviews/scala3-book/ca-contextual-abstractions-intro.md %}
5776
[reference]: {{ site.scala3ref }}/overview.html

0 commit comments

Comments
 (0)