Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 701
Kim Stebel Avatar asked Dec 28 '12 17:12

Kim Stebel


People also ask

What is an implicit Val in Scala?

Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called.

What are for comprehensions in Scala?

Scala offers a lightweight notation for expressing sequence comprehensions. Comprehensions have the form for (enumerators) yield e , where enumerators refers to a semicolon-separated list of enumerators. An enumerator is either a generator which introduces new variables, or it is a filter.

How do I use Implicits in Scala?

Scala provides an implicit keyword that can be used in two ways: method or variable definitions, and method parameter lists. If this keyword is used on method or variable definitions, it tells the compiler that those methods or variable definitions can be used during implicit resolution.


2 Answers

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

like image 181
Kim Stebel Avatar answered Sep 25 '22 23:09

Kim Stebel


Since version 0.3.0-M1, a better-monadic-for compiler plugin provides such functionality.

like image 24
user2840658 Avatar answered Sep 24 '22 23:09

user2840658