A Scala implicit method argument and field example

UPDATE: This example shows how to create an implicit method in Scala 2.9 or older. You can use a slightly simpler approach with Scala 2.10 and newer, which I've documented in this Scala 2.10 implicit class example.

I'm not going to do much writing here today, but instead I'll just demonstrate how an implicit method argument works with implicit fields in Scala. Without any further ado, here's some code:

// define a method that takes an implicit String
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
              yo
              ^

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.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.