17

I have seen this kind of code many times before, most recently at scala-user mailing list:

context(GUI) { implicit ec =>
  // some code
}

context is defined as:

def context[T](ec: ExecutionContext)(block: ExecutionContext => T): Unit = { 
  ec execute { 
    block(ec) 
  } 
}

What purpose does the keeyword implicit achieve when placed in front of a lambda expression parameter?

missingfaktor
  • 90,905
  • 62
  • 285
  • 365
  • possible duplicate: [Scala Functional Literals with Implicits](http://stackoverflow.com/questions/6326132/scala-functional-literals-with-implicits) – kiritsuku Feb 18 '12 at 09:10
  • 1
    For posterity, additional detailed explanation: http://daily-scala.blogspot.com/2010/04/implicit-parameters.html – Eugene Cheipesh Jul 13 '12 at 01:29

1 Answers1

19
scala> trait Conn
defined trait Conn

scala> def ping(implicit c: Conn) = true
ping: (implicit c: Conn)Boolean

scala> def withConn[A](f: Conn => A): A = { val c = new Conn{}; f(c); /*cleanup*/ }
withConn: [A](f: Conn => A)A

scala> withConn[Boolean]( c => ping(c) )
res0: Boolean = true

scala> withConn[Boolean]{ c => implicit val c1 = c; ping }
res1: Boolean = true

scala> withConn[Boolean]( implicit c => ping )
res2: Boolean = true

The last line is essentially a shorthand for the second last.

retronym
  • 54,768
  • 12
  • 155
  • 168