scalaimplicitscala-2.10scala-2.9for-comprehension

Is there a way to declare an implicit val inside a for comprehension?


I have some code with nested calls to flatMap like so:

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

Normally, one would write that as a for comprehension, which makes the code a lot more readable:

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

But I need f to be implicit and I don't see a way to do that with for comprehensions. Is there? Of course I could pass f explicitly, but that would mean bye bye pretty DSL. I'd be interested in answers for both Scala 2.9 and 2.10.

Just to be clear, I would like to do something like this, but it won't compile:

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

EDIT: Maybe a feature request would be a good idea?

EDIT2: This should work with all types that can be used in a for comprehension, so not just with the usual collection types like List or Seq, but also with Future.


Solution

  • No, there isn't. There is a ticket though: https://issues.scala-lang.org/browse/SI-2823