Using Scala implicits
We have addressed implicits in the previous chapters, but here we are to see more examples. Implicit parameters are very similar to default parameters but they use different mechanisms in order to find the default value.
An implicit parameter is one that is passed to a constructor or a method and is marked as implicit, which means that the compiler will search for an implicit value within the scope if you don't provide a value for this parameter. For example:
scala> def func(implicit x:Int) = print(x) func: (implicit x: Int)Unit scala> func <console>:9: error: could not find implicit value for parameter x: Int func ^ scala> implicit val defVal = 2 defVal: Int = 2 scala> func(3) 3
Implicits are very useful for the collection API. For example, the collections API use implicit parameters to supply CanBuildFrom
objects for many methods in these collections. This happens usually because users aren't concerned with these parameters...