Consider the following snippet
def sayManyTimes(a: String): IO[String] = IO(a * 3)
(1 to 2).foldLeft("Read this: ")((c, i) =>
c + sayManyTimes("mayo").unsafeRunSync)
Now, this achieves the desired result, but is not ideal because it’s an unsafe operation.
I would like to restructure the code so that the second line, instead of returning the string, returns the IO that will create the string.
So what's wrong with the for-comprehension?
(1 to 2).foldLeft(IO("Read this: "))((c, i) =>
for {
cc <- c
smt <- sayManyTimes("mayo")
} yield cc + smt)
You can also expand for-comprehension manually:
(1 to 2).foldLeft(IO("Read this: ")){ (c, _) =>
c.flatMap(cc =>
sayManyTimes("mayo").map(cc + _)
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With