Chapter 5. Abstracting Over Context: Type Classes and Extension Methods
In previous editions of this book, this chapter was titled “Implicits” after the mechanism used to implement many powerful idioms in Scala. Scala 3 begins the migration to new language constructs that emphasize purpose over mechanism, to make both learning and using these idioms easier and to address some shortcomings of the prior implementation. The transition will happen over several 3.X releases of Scala to make it easier, especially for existing code bases. Therefore, I will cover both the Scala 2 and 3 techniques, while emphasizing the latter.1
All of these idioms fall under the umbrella abstracting over context. We saw a few examples already, such as the ExecutionContext
parameters needed in many Future
methods, discussed in “A Taste of Futures”. We’ll see many more idioms now in this chapter and the next. In all cases, the idea of context will be some situation where an extension to a type, a transformation to a new type, or an insertion of values automatically is desired for easier programming. Frankly, in all cases, it would be possible to live without the tools described here, but it would require more work on the user’s part. This raises an important point, though. Make sure you use these tools judiciously; all constructs have pros and cons.
How we define and use context abstractions are the most significant changes introduced in Scala 3 that will impact how your Scala code looks in the future (assuming ...
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.