def maxListImpParm[T](elements: List[T]) (implicit orderer: T => Ordered[T]): T =
elements match { case List() =>
throw new IllegalArgumentException("empty list!") case List(x) => x
case x :: rest =>
val maxRest = maxListImpParm(rest)(orderer) if (orderer(x) > maxRest) x
else maxRest
}
Listing 21.3 · A function with an implicit parameter.
The maxListImpParm function, shown in Listing 21.3, is an example of an implicit parameter used to provide more information about a type mentioned explicitly in an earlier parameter list. To be specific, the implicit parameter orderer, of type T => Ordered[T], provides more information about type T—in this case, how to order Ts. Type T is mentioned in List[T], the type of parameter elements, which appears in the earlier parameter list. Because elements must always be provided explicitly in any invocation of maxListImpParm, the compiler will know T at compile time, and can therefore determine whether an implicit definition of type T => Ordered[T] is in scope. If so, it can pass in the second parameter list, orderer, implicitly.
This pattern is so common that the standard Scala library provides implicit “orderer” methods for many common types. You could therefore use this maxListImpParm method with a variety of types:
scala> maxListImpParm(List(1,5,10,3)) res9: Int = 10
scala> maxListImpParm(List(1.5, 5.2, 10.7, 3.14159)) res10: Double = 10.7
scala> maxListImpParm(List("one", "two", "three")) res11: java.lang.String = two
In the first case, the compiler inserted an orderer function for Ints; in the second case, for Doubles; in the third case, for Strings.
Cover · Overview · Contents · Discuss · Suggest · Glossary · Index