I recently learned how to use Scala's native Try
type to handle errors. One good thing with Try
is that I'm able to use for-comprehension and silently ignore the error.
However, this becomes a slight problem with Java's NIO package (which I really want to use).
val p = Paths.get("Some File Path")
for {
stream <- Try(Files.newDirectoryStream(p))
file:Path <- stream.iterator()
} yield file.getFileName
This would have been perfect. I intend to get all file names from a directory, and using a DirectoryStream[Path]
is the best way because it scales really well. The NIO page says DirectoryStream
has an iterator()
method that returns an iterator. For Java's for loop, it's enough and can be used like this:
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
}
However, Scala does not accept this. I was greeted with the error:
[error] /.../DAL.scala:42: value filter is not a member of java.util.Iterator[java.nio.file.Path]
[error] file:Path <- stream.iterator
I try to use JavaConverters
, and it shows it handles Java Iterator
type: scala.collection.Iterator <=> java.util.Iterator
, but when I try to call it in this way: stream.iterator().asScala
, the method is not reachable.
What should I do? How do I write nice Scala code while still using NIO package?