Search code examples
scalascala-streams

forEach in scala shows expected: Consumer[_ >:Path] actual: (Path) => Boolean


Wrong syntax problem in recursively deleting scala files

Files.walk(path, FileVisitOption.FOLLOW_LINKS)
    .sorted(Comparator.reverseOrder())
    .forEach(Files.deleteIfExists)

Solution

  • The issue is that you're trying to pass a scala-style function to a method expecting a java-8-style function. There's a couple libraries out there that can do the conversion, or you could write it yourself (it's not complicated), or probably the simplest is to just convert the java collection to a scala collection that has a foreach method expecting a scala-style function as an argument:

    import scala.collection.JavaConverters._
    
    Files.walk(path, FileVisitOption.FOLLOW_LINKS)
            .sorted(Comparator.reverseOrder())
            .iterator().asScala
            .foreach(Files.deleteIfExists)