How to define a Scala method to take an implicit parameter

NOTE: This example shows how to create a Scala method that takes an implicit parameter. If you’re interested in writing an implicit method, see my Scala 2.10 implicit class example.

A Scala method that takes an implicit parameter

I’m short on time today and won’t give this much of an introduction. Instead, please see the comments as a description of how this example works:

// define a method that takes an implicit String parameter
scala> def yo(implicit s: String) = println("Yo, " + s)
yo: (implicit s: String)Unit

// pass a string to it; it works
scala> yo("Adrian")
Yo, Adrian

// create an implicit String field, which is now "in scope"
scala> implicit val fred = "Fred"
fred: java.lang.String = Fred

// call yo without an argument; it magically finds fred(!)
scala> yo
Yo, Fred

// define an implicit field of a different type (Int)
scala> implicit val one = 1
one: Int = 1

// call yo again, see what happens (it finds fred again)
scala> yo
Yo, Fred

// define a second implicit String
scala> implicit val barney = "Barney"
barney: java.lang.String = Barney

// call yo again; now it can't figure out which String you want 
// it to implicitly use (fred or barney)
scala> yo
<console>:11: error: ambiguous implicit values:
 both value fred in object $iw of type => java.lang.String
 and value barney in object $iw of type => java.lang.String
 match expected type String

As you can see from the code, defining a method argument as implicit makes it like a magnet: If an implicit field of the same type is in scope, it pulls it right in ... with the limit that it can only deal with one implicit field of the matching type at one time.

This technique is used by the Akka library, as was demonstrated in my Akka Futures example, where the Akka library automatically discovers the ActorSystem that's in scope.

I'm out of time for today, but if you haven't used implicit fields and implicit method arguments, I hope that was helpful.