Home > Software engineering >  Scala, ZIO - how to return value from Task?
Scala, ZIO - how to return value from Task?

Time:09-24

I have a simple for-comprehension code:

def nameFormatter(request: SomeRequest) : FormattedData = {
      for {
        config <- ZIO.fromOption(configuration.get(request.name)).orElseFail( new Exception("Unknown config"))
        name = config.data.name.pipe(SomeName)
      } yield FormattedData(
        name,
        request.age
      )
    }

But this method returns:

ZIO[Any, Exception, FormattedData]

I would like to change this method to return only FormattedData, not the whole ZIO. Is it possible? Or maybe I should somehow read returned type and get value from it?

CodePudding user response:

ZIO makes it difficult to do this because it is unsafe and it defeats the purpose of using ZIO. You can tell from the type ZIO[Any, Exception, FormattedData] that it can fail with an Exception if you try to materialise the value.

If you really want to do it:

zio.Runtime.default.unsafeRun(nameFormatter(request))

otherwise you should be composing the rest of your code with the result of nameFormatter(request) and run it with something like:

import zio.{ExitCode, URIO, ZIO}

object Main extends zio.App {
  override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
    (for {
      formattedData <- nameFormatter(request)
      // rest of your code
    } yield ()).exitCode
}

CodePudding user response:

The way to use it is

nameFormatter(request).flatMap { formattedData =>
  // whatever you want to do with the returned value
  // ...
  // the rest of your program
}

or in a for comprehension:

for {
  formattedData <- nameFormatter(request)
  // rest of your program
} yield ()

This DOES NOT answer your question, however it's probably what you wanted to do.

  • Related