scalagenericslambdascala-java-interop

Scala: type hint for lambda


I'm refreshing scala. This looks very simple to me but I can't get it to run:

import java.nio.file.{FileSystems, Files}

object ScalaHello extends App {
    val dir = FileSystems.getDefault.getPath("/home/intelli/workspace")
    Files.walk(dir).map(_.toFile).forEach(println)
}

It throws error at the mapping lambda:

argument expression's type is not compatible with formal parameter type;
 found   : java.util.function.Function[java.nio.file.Path,java.io.File]
 required: java.util.function.Function[_ >: java.nio.file.Path, _ <: ?R]

I suspect it has something to do with providing type hints for the lambda but I can't find anything surfing Google. Much appreciated


Solution

  • Note that Files.walk returns a Java Stream, so map and forEach come from Java.

    Assuming you are using Scala 2.12, your code will work if you either:

    1. Update Scala version to 2.13 (no need to make any other changes in this case)
    2. Specify return type of map:
    Files.walk(dir).map[File](_.toFile).forEach(println)
    
    1. Convert to Scala collections before calling map:
    import scala.collection.JavaConverters._
    Files.walk(dir).iterator().asScala.map(_.toFile).foreach(println)