Chapter 5. Using implicits to write expressive code

 

In this chapter

  • Introduction to implicits
  • Mechanics of the implicit resolution system
  • Using implicits to enhance classes
  • Using implicits to enforce scope rules

The implicit system in Scala allows the compiler to adjust code using a well-defined lookup mechanism. A programmer in Scala can leave out information that the compiler will attempt to infer at compile time. The Scala compiler can infer one of two situations:

  • A method call or constructor with a missing parameter.
  • Missing conversion from one type to another type. This also applies to method calls on an object that would require a conversion.

In both of these situations, the compiler follows a set of rules to resolve missing data and allow the code to compile. When the programmer leaves out parameters, it’s incredibly useful and is done in advanced Scala libraries. When the compiler converts types to ensure that an expression compiles is more dangerous and is the cause of controversy.

The implicit system is one of the greatest assets of the Scala programming language. Using it wisely and conservatively can drastically reduce the size of your code base. It can also be used to elegantly enforce design considerations. Let’s look at implicit parameters in Scala.

5.1. Introduction to implicits

5.2. Enhancing existing classes with implicit views

5.3. Utilize implicit parameters with defaults

5.4. Limiting the scope of implicits

5.5. Summary

sitemap