Hello,
I’m new to kotlin (and a novice programmer in general) and ran into a bit of a snag when iterating over a list of files and filtering them based on their “creationTime” file attribute. The main issue I ran into was dealing with the creation of a Pair<Path, FileTime?> during the collection filtering and handling the null case.
I’m trying to find the most recently created file in a directory.
This is the code I had on my first attempt:
val mostRecentlyCreatedFile = Files.list(downloadFolder).use { path ->
path.asSequence()
.filter { it.isRegularFile() }
.mapNotNull { it to it.getAttribute("creationTime") as? FileTime }
.filter { (_, creationTime) -> creationTime != null}
.maxByOrNull{ it.second!! }
?.first
I didn’t love this because it required using the not-null assertion operator (!!) which I’d like to avoid. I’m assuming !! is required because the FileTime? type is still nullable, so the compiler assumes worst case scenario.
The second attempt was this:
val mostRecentlyCreatedFile = Files.list(downloadFolder).use { path ->
path.asSequence()
.filter { it.isRegularFile() }
.mapNotNull { file ->
val creationTime = Files.getAttribute(file, "creationTime") as? FileTime
creationTime?.let { file to it }
}
.maxByOrNull { it.second }
?.first
}
Similar, but this time the compiler doesn’t complain and I don’t need the !! operator. The .mapNotNull looks a little messy, though.
Question: Is there a reason the compiler understands a null check in the form of " ?.let {} " but not " != null "?
Attempt #3
val mostRecentlyCreatedFile = Files.list(downloadFolder).use { path ->
path.asSequence()
.filter { it.isRegularFile() }
.map { it to it.getAttribute("creationTime") as? FileTime }
.filterIsInstance<Pair<Path, FileTime>>()
.maxByOrNull { it.second }
?.first
}
This gives me no complaints from the compiler and simple lambdas, but the meaning of filterIsInstance is maybe a little opaque.
So my question: Is there an accepted way of filtering out Pair<*, ?> that have a null value? Also, is there something obvious that I’m missing for trying to find the most recently created file that could improve my code?
Any help would be super appreciated - thanks!