42 Implicit and type classes

 

After reading this lesson, you will be able to

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

In the previous unit, you 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 hand, 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 implicits have, you’ll focus on its primary usage. Implicits also have a slightly different syntax between Scala 2 and Scala 3, but their core principles remain the same. You’ll define a function that takes implicit parameters and mark a value as implicit in Scala 2 or as using in Scala 3. You’ll learn how the compiler searches for a match for an implicit parameter, which is a process called implicit resolution. You’ll also see how to express ad hoc polymorphism using a pattern called type class using the keywords implicit in Scala 2 and given . . . with in Scala 3. 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

 

Summary

 
 

Answers to quick checks

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest