Home > Software design >  Scala: How do I convert this flatMap/map into a for-comprehension?
Scala: How do I convert this flatMap/map into a for-comprehension?

Time:09-28

I am having trouble with understanding how to convert this into a for-comprehension. Could someone please explain how this can be done?

    (parseCommand(x)
      .flatMap { c =>
        calculate(c).map(r => renderResult(c, r))
      })
      .left
      .map(e => e.value)
      .merge
    ```

CodePudding user response:

You haven't provided enough information to answer your question.

  • What type does parseCommand() return?
  • What type does calculate() return?
  • Why translate to a for comprehension? What's your goal?

Assuming that parseCommand() and calculate() return the same or compatible types, the the 1st map() and flatMap() can be translated like so:

(for {
       c <- parseCommand(x)
       r <- calculate(c)
     } yield renderResult(c, r)
).left
 .map(e => e.value)
 .merge
 ...

The 2nd map() can't be folded in to this for because there can be only one map() per for comprehension. You could, however, turn it into its own, nested, for comprehension, but remember that it makes no difference to the compiler, so the only real reason to use for is to enhance code readability, and nested fors seldom achieve that.

CodePudding user response:

In the below link, you may find some helpful information about converting flatMap/map into For comprehension :

https://stackoverflow.com/questions/14598990/confused-with-the-for-comprehension-to-flatmap-map-transformation#:~:text=The for comprehension is a,with an inner type A .

CodePudding user response:

I managed to convert it like this:

(for {
      c <- parseCommand(x)
      r <- calculate(c)
    } yield renderResult(c, r)).left.map(x => x.value).merge
  }
  • Related