Search code examples
scalaiomonadsscala-cats

Retrieving value wrapped in IO


Is there a way to get the value inside an IO, without using unsafeRunSync() ?

For instance, I have a

val x : IO[Long] = IO$9125

I want to get the Long value in order to perform some computation on it without using unsafeRunSync()


Solution

  • You shouldn't want to get the value from monadic context. This is incorrect way of thinking (retrieving the value from a context is typical for Comonad).

    Monads in pictures.

    What is a monad?

    You shouldn't want to get A from Option[A], A from List[A], A from Future[A], A from IO[A]... As soon as you get into monadic calculation you should continue to work inside the monad, with .map, .flatMap, for-comprehensions etc.

    For example for val x: IO[Long] = ... inside

    for {
      long <- x
      ...
    } yield ...
    

    long has type Long.

    So you do calculations inside IO and execute unsafeRunSync() or unsafePerformIO() once at the very end.