Kim*_*bel 27 scala implicit for-comprehension scala-2.9 scala-2.10
我有一些代码嵌套调用flatMap,如下所示:
foo.flatMap(implicit f => bar(123).flatMap(b =>
/* and so on... implicit f is still in scope here.*/
))
Run Code Online (Sandbox Code Playgroud)
通常,人们会将其写为理解,这使得代码更具可读性:
for {
f <- foo
b <- bar(123)
/* yet more method calls that need f as an implicit parameter*/
}
Run Code Online (Sandbox Code Playgroud)
但我需要f
暗示,我不认为有办法用于理解.在那儿?当然我可以明确地传递f,但这意味着再见DSL.我对Scala 2.9和2.10的答案感兴趣.
为了清楚起见,我想做这样的事情,但它不会编译:
for {
implicit f <- foo
b <- bar(123) //bar takes implicit argument
/* yet more method calls that need f as an implicit parameter*/
}
Run Code Online (Sandbox Code Playgroud)
编辑:也许一个功能请求是一个好主意?
EDIT2:这应该适用于所有可以用于理解的类型,因此不仅仅是通常的集合类型,如List
或Seq
,还有Future
.
Kim*_*bel 12
不,没有.虽然有一张票:https://issues.scala-lang.org/browse/SI-2823
例如, Scala 3 (Dotty)在 for 推导式中启用给定(隐式)
Starting dotty REPL...
scala> for {
| given Int <- Some(41)
| y <- Some(1)
| } yield summon[Int] + y
val res0: Option[Int] = Some(42)
Run Code Online (Sandbox Code Playgroud)
Martin 指出,只要对类型进行注释,Dotty 就已经支持更雄心勃勃的版本。例如,在 Dotty 中,可以编译:
implicit val (a: Int, b: String) = (3, "foo")