【问题标题】:How to perofrm a try and catch in ZIO?如何在 ZIP 中执行 try and catch?
【发布时间】:2021-03-19 23:11:15
【问题描述】:

我使用 ZIO 的第一步,我正在尝试将此 readfile 函数转换为兼容的 ZIO 版本。

下面的sn-p可以编译,但是我没有关闭ZIO版本的源码。我该怎么做?

 def run(args: List[String]) =
    myAppLogic.exitCode

  val myAppLogic =
    for {
      _    <- readFileZio("C:\\path\\to\file.csv")
      _    <- putStrLn("Hello! What is your name?")
      name <- getStrLn
      _    <- putStrLn(s"Hello, ${name}, welcome to ZIO!")
    } yield ()

  def readfile(file: String): String = {
    val source = scala.io.Source.fromFile(file)
    try source.getLines.mkString finally source.close()
  }

  def readFileZio(file: String): zio.Task[String] = {
    val source = scala.io.Source.fromFile(file)
    ZIO.fromTry[String]{
      Try{source.getLines.mkString}
    }
    
  }

【问题讨论】:

    标签: scala io zio


    【解决方案1】:

    解决您的问题的最简单方法是使用bracket 函数,其本质上与 try-finally 块具有相似的目的。它作为关闭资源的第一个参数效果(在您的情况下为Source)和使用它的第二个效果。

    所以你可以重写readFileZio,比如:

    def readFileZio(file: String): Task[Iterator[String]] =
      ZIO(Source.fromFile(file))
        .bracket(
          s => URIO(s.close),
          s => ZIO(s.getLines())
      )
    

    另一种选择是使用ZManaged,这是一种封装了打开和关闭资源操作的数据类型:

    def managedSource(file: String): ZManaged[Any, Throwable, BufferedSource] = 
       Managed.make(ZIO(Source.fromFile(file)))(s => URIO(s.close))
    

    然后你可以这样使用它:

    def readFileZioManaged(file: String): Task[Iterator[String]] =
        managedSource(file).use(s => ZIO(s.getLines()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2016-02-19
      相关资源
      最近更新 更多