0

在 getstarted zio doc 页面中有这个简单的例子,但我无法运行它,有什么简单的代码可以使这个片段工作(有问题并能够在控制台中回答)?

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
  }
}
4

3 回答 3

1
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)

  }
}
于 2021-01-14T14:54:14.223 回答
1

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

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
}

这样,您可以将所有内容推到世界末日并干净地处理错误。

于 2021-01-15T01:54:53.930 回答
0
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)
}
于 2021-02-10T00:44:07.220 回答