在Scala中将静态内部接口实现为匿名类



我想在Scala中使用NIO.2特性(类在java.NIO.file中):

在Java中,我会做:

Files.newDirectoryStream(Paths.get("/tmp"), new DirectoryStream.Filter<Path>() {
  @Override
  public boolean accept(Path entry) throws IOException {
    return false;
  }
});

我怎样才能在Scala中做到这一点?FitlerDirectoryStream接口中的静态接口。

谢谢。

编辑:如果你想向我推荐另一种列出文件的库/方法,请不要回复。我主要对主要问题感兴趣。

不能100%确定您是否要求在scala:中对该代码进行文字转换

Files.newDirectoryStream(Paths.get("/tmp"), new DirectoryStream.Filter[Path] {
  def accept(entry: Path) = false
})

还是别的什么?您可以添加一个隐式转换:

class PathPredicateFilter(p: Path => Boolean) 
  extends DirectoryStream.Filter[Path] {
  def accept(entry: Path) = p(entry)
}
implicit def PathPredicate_Is_DirectoryStreamFilter(p: Path => Boolean) 
  = new PathPredicateFilter(p)

现在你可以这样做了:

Files.newDirectoryStream(Paths.get("/tmp"), (p: Path) => false /* your code here */)

最新更新