如何 运行 一个简单的 ZIO 理解片段

How to run a trivial ZIO for comprehension snippet

在 getstarted zio 文档页面中有这个 trivial exemple,但我不能 运行 它,可以用什么简单的代码来使这个片段工作(有问题并能够回答在控制台中)?

import zio.console.{getStrLn, putStrLn}
object Bug41 {
  def main(args: Array[String]): Unit = {
    println("Start")
    val program =
      for {
        _    <- putStrLn("Hello! What is your name?")
        name <- getStrLn
        _    <- putStrLn(s"Hello, ${name}, welcome to ZIO!")
      } yield ()
    program.run
  }
}
object Bug41 {

  val program: RIO[Console, Unit] =
    for {
      _    <- putStrLn("Hello! What is your name?")
      name <- getStrLn
      _    <- putStrLn(s"Hello, $name, welcome to ZIO!")
    } yield ()

  def main(args: Array[String]): Unit = {

    val runtime: Runtime[zio.ZEnv] = zio.Runtime.default.mapPlatform(_.withReportFailure(cause => println(cause)))

    runtime.unsafeRun(program)

  }
}

如果您只是与 ZIO 交互,您可以使用内置的 zio.App

object Bug41 extends zio.App {
  def run(args: List[String]): URIO[ZEnv, ExitCode] = 
    (for {
      _    <- putStrLn("Hello! What is your name?")
      name <- getStrLn
      _    <- putStrLn(s"Hello, $name, welcome to ZIO!")
    } yield ()).exitCode
}

这样你就可以把所有的事情都推到世界尽头,并且干净利落地处理错误。

import zio._
import zio.console._
import zio.internal.Platform

object Logic {
  val main: RIO[Console, Unit] =
    for {
      _    <- console.putStrLn("Hello! What is your name?")
      name <- console.getStrLn
      _    <- console.putStrLn(s"Hello, $name, welcome to ZIO!")
    } yield ()
}

object Bug41 extends zio.App {
  def run(args: List[String]): URIO[ZEnv, ExitCode] = Logic.main.exitCode

  override val platform: Platform = Platform.default.withReportFailure(println)
}