之前我见过很多次这种代码,最近一次是在scala-user邮件列表中:
context(GUI) { implicit ec =>
// some code
}
context
定义为:
def context[T](ec: ExecutionContext)(block: ExecutionContext => T): Unit = {
ec execute {
block(ec)
}
}
当放置在lambda表达式参数前面时,keeyword implicit
的目的是什么?
答案 0 :(得分: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
最后一行基本上是第二行的简写。