Adding functions for multiple types

If we look back at the beginning of this chapter, where we made Adder work with numeric types, we will see that our last implementation of Adder would require us to define an operation separately for each different numeric type. Is there a way to achieve what we showed in the beginning of the chapter here as well? Yes, there is, and this is done as follows:

implicit def numeric2Adder[T : Numeric]: Adder[T] = new Adder[T] {  override def sum(a: T, b: T): T = implicitly[Numeric[T]].plus(a, b)}

We just defined another implicit conversion, and it will take care of the right things for us. Now, we can also write the following code:

System.out.println(s"The sum of 1.2 + 6.5 is ${sum(1.2, 6.5)}")
Ad hoc polymorphism ...

Get Scala Design Patterns - Second 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.