Reputation: 13088
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.
Upvotes: 1
Views: 2242
Reputation: 5093
For all the folks looking for answer in 2019 - there's been a minor change in the API.
import scalaz.zio._
object RTS extends DefaultRuntime
class Service {
val program: UIO[String] = ???
def mixPureImpure: String = {
println("Calling service")
RTS.unsafeRun(program)
}
}
Upvotes: 3
Reputation: 4817
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.
Upvotes: 6
Reputation: 41
There is no way to implement a pure function that takes IO[Nothing, T]
and returns T
.
It is so because the first type argument of ZIO's IO[_, _]
describes errors that can happen inside an IO
-wrapped computation. IO[Nothing, T]
describes a computation that cannot fail, but still it encapsulates a side-effectful computation. That is why you cannot get value of type T
outside of it in a pure function.
Just talking about physical possibility, since Scala is not a pure language, you have a possibility to write a function that takes IO[Nothing, T]
and returns T
but you are really discouraged to do this by the design and ideology of ZIO.
Upvotes: 4