0

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

3
  • What is your Scala version? What is your Java version? Commented Feb 5, 2023 at 13:47
  • And also please show your build file (build.sbt?). Especially scalacOptions. Commented Feb 5, 2023 at 13:51
  • Does anything change for you if you specify .map[File]((_: Path).toFile)? Commented Feb 5, 2023 at 14:16

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Cool. So it seems to be 2.12
Kolmar, thanks for the explanation: I somehow assumed that the stages of Scala streams would apply directly ...but as you explain, I was applying the transformations from Java streams!
@Kolmar "2.13 (no need to make any other changes in this case)" This seems to depend on scalacOptions sometimes. With -Ydelambdafy:inline .forEach(println) doesn't compile in 2.13 (class type required but java.util.function.Consumer[_ >: java.io.File] found) while .forEach(println(_)) does. With -Ydelambdafy:method (default) .forEach(println) compiles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.