A good example in the standard library is the definition of unzip
on e.g. a List[A]
:
def unzip[A1, A2](implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2])
The goal is to allow the following to compile:
val (ks, vs) = List('a -> 1, 'b -> 2, 'c -> 3).unzip
But not this:
val (ks, vs) = List(1, 2, 3).unzip
This is accomplished via an implicit argument that witnesses that the type of the list can be viewed as a pair. In the example above this evidence is provided by Predef.conforms
, which for any type A
will implicitly provide an instance of A <:< A
, which is a subtype of A => A
. The instance provided by conforms
will of course just be the identity function.
If you look at the definition of unzip
, you'll see how the evidence is used in this case:
def unzip[A1, A2](implicit asPair: A => (A1, A2)): (CC[A1], CC[A2]) = {
val b1 = genericBuilder[A1]
val b2 = genericBuilder[A2]
for (xy <- sequential) {
val (x, y) = asPair(xy)
b1 += x
b2 += y
}
(b1.result, b2.result)
}
I.e., it's used to deconstruct the items in the sequence. Remember that this method is defined on any List[A]
, so writing plain old val (x, y) = xy
wouldn't compile.
Other applications of implicit evidence may have different goals (some quite complex) and may use the implicit evidence in different ways (it's not necessarily just a function), but the basic pattern is generally going to be more or less the same as what you see with unzip
.