ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Scala Using
    scala/basic 2022. 12. 19. 00:03

    scala 2.13 버전부터 scala.util.Using 이 추가되었다.

    cats-effect 의 Resource 또는 zio 의 Scope 처럼 resource 관리를 위해 사용될 수 있다.

    AutoCloseable Resource 에서 사용

    기본적으로 Using.resource(..) 혹은 Using.resources(..) 를 이용하자. (필요하면 Try 로 감싼다)

     

    https://www.scala-lang.org/api/2.13.6/scala/util/Using$$Releasable.html  을 보면 아래와 같은 내용이 있다.

    An instance of Releasable is needed in order to automatically manage a resource with Using. An implicit instance is provided for all types extending java.lang.AutoCloseable.

    import scala.io.{BufferedSource, Source}
    import scala.util.{Try, Using}
    
    object ScalaApp {
      def main(args: Array[String]): Unit = {
        val linesTry: Try[List[String]] = Using(Source.fromFile("input.txt"))(source => source.getLines().toList)
    
        // can throw Exception
        val lines: List[String] = Using.resource(Source.fromFile("input.txt"))(source => source.getLines().toList)
    
        // can throw Exception
        val allLines: Seq[String] =
          Using.resources(Source.fromFile("input.txt"), Source.fromFile("input2.txt")) { (input, input2) =>
            input.getLines().toList ++ input2.getLines().toList
          }
      }
    }

     

    Custom Resource 에서 사용

    import scala.util.Using
    
    class MyConnection {
      def echo(): Unit = println("Hi~")
      def stop(): Unit = println("stop called")
    }
    
    object MyConnection {
      implicit val myConnectionImpl: Using.Releasable[MyConnection] = (resource: MyConnection) => resource.stop()
    }
    
    object ScalaApp {
      def main(args: Array[String]): Unit =
        Using(new MyConnection)(connection => connection.echo())
    }
    
    // 출력 결과
    // Hi~
    // stop called

    'scala > basic' 카테고리의 다른 글

    Future[Try[A]] <=> Future[A] 상호간 변환하기  (0) 2023.01.16
    Error Modeling (with Exception)  (0) 2023.01.16
    F-Bound  (0) 2022.11.12
    Scala Closure  (0) 2022.10.21
    java callback 을 scala Future 로 바꾸기  (0) 2022.07.16

    댓글

Designed by Tistory.