Greetings all!
First of all, I’m relatively new to Scala, so I’m sorry if I commit any naming mistake, and you may consider anything here as passible for change, refactoring or even total reconsideration of my own
I’ve been working on a personal project in Scala 2.12.19, aiming to create unit tests for most of it. In order to retrieve the content of system files, I’ve decided to use the Java API java.nio.file
, which I’ve heard is faster and more secure, without needing to close the access, which is a valid advantage for my project. I’ve imported the Files
and Path
classes, both Java static classes.
To use them in the most testable manner in Scala (therefore, enabling mocks and avoiding spies), I’ve chosen to create a higher-order method that will get the files, passing the functions as arguments for it, with the actual ones I’ll use set as default, as shown below:
import java.nio.charset.{Charset, StandardCharsets}
import java.nio.file.{Files, Path}
class FileCollector {
val filePath = "/any/file/path"
def getFileContent(
path_getter: ((String, String*) => Path) = Path.of,
file_reader: ((Path) => Array[Byte]) = Files.readAllBytes,
charset: Charset = StandardCharsets.UTF_8
): String = {
new String(
file_reader(path_getter(filePath)),
charset
)
}
}
When compiling using SBT 1.9.8 (Java 22), it throws the following error regarding the Path.of
default method, set inside the path_getter
:
type mismatch;
found : (x$1: java.net.URI)java.nio.file.Path <and> (x$1: String, x$2: String*)java.nio.file.Path
required: (String, String*) => java.nio.file.Path
It seems that the Path.of
method is a Java overloaded method, to which Scala does not use the arguments types set to resolve which method option to use.
I’ve already tried to switch to Scala 2.13.13, in which the error first changes to requiring to use Seq instead of repeated parameters due to version updates, and then falls back to the same error when using Seq.
Does anyone know how to handle this problem properly, or have any other suggestions of how to approach the same goals?