Chapter 6. Abstracting Over Context: Using Clauses

In Chapter 5, we began our discussion of the powerful tools and idioms in Scala 2 and 3 for abstracting over context. In particular, we discussed type classes, extension methods, and implicit conversions as tools for extending the behaviors of existing types.

This chapter explores using clauses, which work with given instances to address particular design scenarios and to simplify user code.

Using Clauses

The other major use of context abstractions is to provide method parameters implicitly rather than explicitly. When a method argument list begins with the keyword using (Scala 3) or implicit (Scala 2 and 3), the user does not have to provide values explicitly for the parameters, as long as given instances or implicit values are in scope that the compiler can use instead.

In Scala 2 terminology, those method parameters were called implicit parameters, and the whole list of parameters was an implicit parameter list or implicit parameter clause. Only one such list was allowed, and it held all the implicit parameters. In Scala 3, they are context parameters and the whole parameter list is a using clause. There can be more than one using clause.1 Here is an example:

class BankAccount(...):
  def debit(amount: Money)(using transaction: Transaction)
  ...

Here, the using clause starts with the using keyword and contains the context parameter transaction.

The values in scope that can be used to fill in these parameters are called implicit ...

Get Programming Scala, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.