Home > Enterprise >  Turn an IO[List[String]] in scala to a String that's comma separated
Turn an IO[List[String]] in scala to a String that's comma separated

Time:07-22

I have a IO[List[String]] (of urls string) that I'd like to convert into a comma separated String. Is there a join or something I can use? I'm getting caught up on the IO type.

CodePudding user response:

You can use the map method to apply a function to the result of the IO action:

def toCommaSeparated(
  io: IO[List[String]]
): IO[String] =
  io.map(_.mkString(", "))

CodePudding user response:

There is a way. You could use unsafeRunSync() or unsafePerformIO() once at the end to evaluate the encapsulated code.

But I advise against it, because IO's purpose is to encapsulate side-effecting code in the first place, that would otherwise make code impure, to be wrapped inside the IO and unable to evaluate unless and until we want it to do so.

In a monadic way you write code using the map and flatMap functions to compose other functions and ideally call one of these unsafe operations only once, at the end. Getting the value out of a monadic context is contrary to it's purpose in the first place, and usually hints a code smell in your design.

A more logical approach would be to use a Comonad, which has an extract method that instead takes an F[A] and extracts the A. You must be sure you can get an A from an F[A] when calling it though (e.g. you cannot get an A from a List[A] if the list is empty).

  • Related