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

mis*_*tor 16 scala implicit

我以前见过这种代码很多次,最近一次是在scala-user邮件列表中:

context(GUI) { implicit ec =>
  // some code
}
Run Code Online (Sandbox Code Playgroud)

context 定义为:

def context[T](ec: ExecutionContext)(block: ExecutionContext => T): Unit = { 
  ec execute { 
    block(ec) 
  } 
}
Run Code Online (Sandbox Code Playgroud)

implicit当keeyword 置于lambda表达式参数前面时,它的目的是什么?

ret*_*nym 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
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你的要点.出演了它. (2认同)