'java try-with-resource not working with scala
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(Stream<String> stream = Files.lines(Paths.get("somefile.txt"))){
stream.forEach(System.out::println); // will do business process here
}catch (IOException e) {
e.printStackTrace(); // will handle failure case here
}
But the compiler throws error like
◾not found: value stream
◾A try without a catch or finally is equivalent to putting its body in a block; no exceptions are handled.
Not sure what is the problem. Am new to using Java NIO, so any help is much appreciated.
Solution 1:[1]
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
Solution 2:[2]
You have the already mentioned in one of the answers approach:
def autoClose[A <: AutoCloseable, B](resource: A)(code: A ? B): B = {
try
code(resource)
finally
resource.close()
}
But I think the following is much more elegant:
def autoClose[A <: AutoCloseable, B](resource: A)(code: A ? B): Try[B] = {
val tryResult = Try {code(resource)}
resource.close()
tryResult
}
With the last one IMHO it's easier to handle the control flow.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Erbureth |
| Solution 2 | Johnny |
