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

问题描述 投票:24回答:3

我有一些嵌套调用flatMap的代码,如下所示:

foo.flatMap(implicit f => bar(123).flatMap(b =>
  /* and so on... implicit f is still in scope here.*/
))

通常,人们会将其写为理解,这使得代码更具可读性:

for {
  f <- foo
  b <- bar(123)
  /* yet more method calls that need f as an implicit parameter*/
}

但我需要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*/
}

编辑:也许一个功能请求是一个好主意?

编辑2:这应该适用于所有可以用于理解的类型,因此不仅使用ListSeq等常用集合类型,还可以使用Future

scala implicit scala-2.10 scala-2.9 for-comprehension
3个回答
10
投票

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


3
投票

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


-1
投票

这段代码怎么样?

// prerequisites
val (a,b) = (List(1,2,3), List(3,4,5,7,9))
def tree(n: Int)(implicit s: Int) = " "*s + "0"*n + (if (s+3 < n) "*" else "")

// actual for
@volatile implicit var s = 0
for (i <- a if ({s = i; true}); j <- b) 
  println(tree(j))

// 000
// 0000
// 00000*
// 0000000*
// 000000000*
//  000
//  0000
//  00000
//  0000000*
//  000000000*
//   000
//   0000
//   00000
//   0000000*
//   000000000*
© www.soinside.com 2019 - 2024. All rights reserved.