I think there is the consensus that, nowadays, Path
should be used instead of File
in Java code. But what about Kotlin? Kotlin has some nice extension functions on File
which make it more usable than in plain Java. Sometimes, even, those extension functions are missing on Path
. So I’m unsure what to use. Sure, one can always switch from on to the other via toFile()
and toPath()
. But, I guess, there should be some consistency for type declarations on properties, parameters etc. in a code base.
So, I wonder, what are the plans of Kotlin stdlib for Path
? If all extension functions available on File
would be ported to Path
as well, I guess the natural choice would be Path
again. But until then, its kind of a mess. What is your choice?
1 Like
@thumannw Have you checked those in kotlin.io.path
package? Tell if you miss something there.
@darksnake To be precise, most Path
extensions are available since Kotlin 1.5
1 Like
I read from from your answer, that extensions on File and Path are intended to be equivalent and, in fact, are equivalent since 1.8.0? That’s good.
I missed methods to list the directory entries on Path. There is the “listDirectoryEntries” extension on Path, but this accepts a glob String. Whereas java.io.File has the “list” and “listFiles” methods which can be used with predicates. Globs are nice, but sometimes proper predicates are more powerful and/or less error-prone.
that extensions on File and Path are intended to be equivalent
Not entirely equivalent, but providing equivalent functionality more or less.
There is the “listDirectoryEntries” extension on Path, but this accepts a glob String. Whereas java.io.File has the “list” and “listFiles” methods which can be used with predicates. Globs are nice, but sometimes proper predicates are more powerful and/or less error-prone.
Valid point, newDirectoryStream
in Java has an overload with a predicate, so we could have something like that too. Makes sense to report a feature request.
Meanwhile you can use useDirectoryEntries
instead. It takes a lambda where entries are available as a sequence and you can filter it lazily, e.g.
val filtered = path.useDirectoryEntries { entries ->
entries.filter { "foo" in it.fileName }.toList()
}
Although for the functions useDirectoryEntries
and forEachDirectoryEntry
which are similar to listDirectoryEntries
, adding an overload with a predicate will result in the signatures with two lambdas, which would not be very beautiful on a call site:
path.forEachDirectoryEntry({ it.fileName.contains(...) }) {
println(it)
}
1 Like