September 2018
Intermediate to advanced
398 pages
9h 43m
English
Implicit conversions are often used to add additional methods to an existing type. This is called the pimp my library pattern. For instance, if we want to add a square method on the Int type, we can proceed as follows. Type the following code in a Scala console:
scala>class IntOps(val i: Int) extends AnyVal { def square: Int = i * i}scala> implicit def intToIntOps(i: Int): IntOps = new IntOps(i)intToIntOps: (i: Int)IntOpsscala> 5.squareres0: Int = 25
The 5 gets implicitly converted to IntOps, which provides the square method.
Note that IntOps extends AnyVal. This extension makes it a value class. The benefit of a value class is that the compiler will avoid allocating a new object when we call the square method. The produced ...
Read now
Unlock full access