I have the following sample code:
def transferFiles(files: List[String], move: Boolean = false ): Unit = {
for(file <- files) {
if (move) {
println(s"Move $file")
} else {
println(s"Copy $file")
}
}
}
val files = List("autoexec.bat", "config.sys")
transferFiles(files)
This will print as expected:
Copy autoexec.bat
Copy config.sys
I would like to optimize it to be in a fashion similar to
def transferFiles(files: List[String], move: Boolean = false ): Unit = {
def transfer = () => {
println("Checking flag")
if (move) {
(file: String) => println(s"Move $file")
} else {
(file: String) => println(s"Copy $file")
}
}
for(file <- files) {
transfer()(file)
}
}
val files = List("autoexec.bat", "config.sys")
transferFiles(files)
which prints:
Checking flag
Copy autoexec.bat
Checking flag
Copy config.sys
The thing is that I want to see Checking flag
only once and I don't want to call the function with double parentheses transfer()(file)
. I believe Higher Order functions can be used for this purpose, but I do not know how to make it work. Is anyone able to patch my code so that it fulfils at least the first requirement (only one print of the flag checking)?