diff --git a/_overviews/scala3-book/taste-contextual-abstractions.md b/_overviews/scala3-book/taste-contextual-abstractions.md index c1db055e9e..9e25f5029a 100644 --- a/_overviews/scala3-book/taste-contextual-abstractions.md +++ b/_overviews/scala3-book/taste-contextual-abstractions.md @@ -19,12 +19,18 @@ Those parameters are called _Context Parameters_ because they are inferred by th For instance, consider a program that sorts a list of addresses by two criteria: the city name and then street name. +{% tabs contextual_1 %} +{% tab 'Scala 2 and 3' for=contextual_1 %} + ```scala val addresses: List[Address] = ... addresses.sortBy(address => (address.city, address.street)) ``` +{% endtab %} +{% endtabs %} + The `sortBy` method takes a function that returns, for every address, the value to compare it with the other addresses. In this case, we pass a function that returns a pair containing the city name and the street name. @@ -39,10 +45,25 @@ It is convenient to omit it because we know `String`s are generally compared usi However, it is also possible to pass it explicitly: +{% tabs contextual_2 class=tabs-scala-version %} +{% tab 'Scala 2' for=contextual_2 %} + +```scala +addresses.sortBy(address => (address.city, address.street))(Ordering.Tuple2(Ordering.String, Ordering.String)) +``` + +{% endtab %} +{% tab 'Scala 3' for=contextual_2 %} + ```scala addresses.sortBy(address => (address.city, address.street))(using Ordering.Tuple2(Ordering.String, Ordering.String)) ``` +in Scala 3 `using` in an argument list to `sortBy` signals passing the context parameter explicitly, avoiding ambiguity. + +{% endtab %} +{% endtabs %} + In this case, the `Ordering.Tuple2(Ordering.String, Ordering.String)` instance is exactly the one that is otherwise inferred by the compiler. In other words both examples produce the same program. @@ -51,7 +72,5 @@ They help developers write pieces of code that are extensible and concise at the For more details, see the [Contextual Abstractions chapter][contextual] of this book, and also the [Reference documentation][reference]. - - [contextual]: {% link _overviews/scala3-book/ca-contextual-abstractions-intro.md %} [reference]: {{ site.scala3ref }}/overview.html