当关键字'implicit'放在lambda表达式参数前面时,它意味着什么?

时间:2012-02-18 09:05:08

标签: scala implicit

之前我见过很多次这种代码,最近一次是在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的目的是什么?

1 个答案:

答案 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

最后一行基本上是第二行的简写。