Search code examples
scalascalazzio

In ZIO, is there a way to transform an IO[Nothing, T] to T, and if not, why not?


After considering errors and converting IO[E, T] to an IO[Nothing, T] we may directly refer to the value as being of type T instead of IO[Nothing, T]. This allows us to return a value of type T without resorting to the use of var and IO.map. Is there a way to do this, and if not, why not?

No solution was found in the current README of ZIO.


Solution

  • IO[E, T] is just a description of a program that can either return an error E or produce a value T.

    To actually produce this value you need to run this program.

    ZIO by design encourages pushing the impure side effects to the very edge of your program which is the main function. In fact you don't need to explicitly call unsafeRun anywhere in your code, as ZIO's App trait takes care of this for you.

    That being said, if you still need to do it, say becouse you're not ready to refactor your whole application, you can use the RTS trait (RTS stands for runtime system).

    import scalaz.zio._
    
    class SomeService extends RTS {
    
      val pureProgram: IO[Nothing, String] = ???
    
      // will throw if pureProgram returns error branch
      def impureMethod: String {
        println("Part of my program is pure, but not all of it")
        unsafeRun(pureProgram)
      }
    }
    

    See ZIO RTS Scaladoc for other run methods.