Assuming getData() returns an IO[_] and has all its side effects suspended, I fail to see any difference between
getData().map(d => println(d.toString))
and
getData().flatMap(d => IO(println(d.toString)))
Am I missing something? are both results impure? are both pure? should I avoid the shorter, more readable .map() version for any particular reason?
I think the two are equivalent and both have suspended side effects, so my preference goes to the first one.
Both are wrong actually, you should use
getData().flatMap(IO.println):)Pedantic answers outside, while you are technically correct that the
mapone would behave exactly the same in isolation (and in the happy path). It is a good idea to get used to the mental model of composing programs rather than mixing pure and impure code because that will lead to a bug sooner rather than later.Note that doing
map(println)is kind of common when doing quick debugs that should not reach production; although for this use case, one should prefer thedebugmethod.Finally, the reason to prefer
IO.printlnoverIO(println)is that printing is blocking, even if short compared to other blocking operations. And this helper manages that for us in the proper way.BTW, if
getDatadoes not need parameters, it shouldn't have an empty parameter list, it could even be aval.