Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the keyword 'implicit' mean when it's placed in front of lambda expression parameter?

Tags:

scala

implicit

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?

like image 758
missingfaktor Avatar asked Feb 18 '12 09:02

missingfaktor


1 Answers

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.

like image 145
retronym Avatar answered Oct 17 '22 05:10

retronym