chapter forty two

42 Implicit and Type Classes

 

After reading this lesson, you will be able to:

  • Define a function that takes implicit parameters
  • Mark values as implicit
  • Use the type class pattern to express ad-hoc polymorphism.

In the previous unit, you have learned about collections and error handling. In this lesson, you'll discover a feature of the Scala language called implicit. It is one of its most controversial traits. On one side, it allows you to write less code and express extremely powerful abstractions. On the other hand, it can make your program more difficult to understand, and it increases its compilation time if misused. In this lesson, rather than introducing you to all the uses that implicits have, you’ll focus on its primary usage. You’ll define a function that takes implicit parameters and mark a value as implicit for it. You’ll learn how the compiler searches for a match for an implicit parameter, which is a process called implicit resolution. Also, you’ll see how to express ad hoc polymorphism using a pattern called type class. In the capstone, you will use implicits to define the number of threads to use when reading and writing the questions and answers to the database for your quiz application.

42.1   Implicit Parameters and Values

42.2   Implicit Resolution

42.3   Type Classes

42.4   Summary

42.5   Answers to Quick Checks