java try-with-resource not working with scala

后端 未结 3 1689
-上瘾入骨i
-上瘾入骨i 2021-02-05 11:44

In Scala application, am trying to read lines from a file using java nio try-with-resource construct.

Scala version 2.11.8
Java version 1.8

try(Strea         


        
3条回答
  •  礼貌的吻别
    2021-02-05 12:09

    Alternatively, you can use Choppy's (Disclaimer: I am the author) TryClose monad do this in a for-comprehension in a composeable manner similar to Scala's Try.

    val ds = new JdbcDataSource()
    val output = for {
      conn  <- TryClose(ds.getConnection())
      ps    <- TryClose(conn.prepareStatement("select * from MyTable"))
      rs    <- TryClose.wrap(ps.executeQuery())
    } yield wrap(extractResult(rs))
    

    Here's how you would do it with your stream:

    val output = for {
      stream  <- TryClose(Files.lines(Paths.get("somefile.txt")))
    } yield wrap(stream.findAny())
    

    More info here: https://github.com/choppythelumberjack/tryclose

提交回复
热议问题