有没有办法在for comprehension中声明一个隐含的val?

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:这应该适用于所有可以用于理解的类型,因此不仅仅是通常的集合类型,如ListSeq,还有Future.

Kim*_*bel 12

不,没有.虽然有一张票:https://issues.scala-lang.org/browse/SI-2823

  • 这个问题8周年纪念日,耶 (8认同)
  • 仅供参考,此问题自 Scala 3.0 起已修复 (2认同)

小智 11

从 0.3.0-M1 版本开始,一个更好的 monadic-for编译器插件提供了这样的功能。


Mar*_*lic 6

例如, 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)

根据隐式理解/模式匹配 SIP 跟踪 #6

Martin 指出,只要对类型进行注释,Dotty 就已经支持更雄心勃勃的版本。例如,在 Dotty 中,可以编译:implicit val (a: Int, b: String) = (3, "foo")