Simple Scala pattern for “using/try-with-resources” (Automatic Resource Management)

后端 未结 7 1795
别那么骄傲
别那么骄傲 2020-12-06 00:37

C# has using with the IDisposable interface. Java 7+ has identical functionality with try and the AutoCloseable interface

相关标签:
7条回答
  • 2020-12-06 01:38

    Your approach with a single simple loan pattern is working fine as long as you don't need to work with several resources, all needing to be managed. That's allowed with scala-arm monadic approach.

    import resource.managed
    
    managed(openResA).and(managed(openResB)) acquireFor { (a, b) => ??? }
    
    val res = for {
      a <- managed(openResA)
      b <- managed(openResB)
      c <- managed(openResC)
    } yield (a, b, c)
    
    res acquireAndGet {
      case (a, b, c) => ???
    }
    

    Main functions to know in scala-arm is resource.managed and .acquired{For,AndGet}, not really complex btw.

    0 讨论(0)
提交回复
热议问题