Can the below function be less verbose with a Lambda expression? How can I trim it down? It is calling the FilenameFilter.accept()
Java method.
val files = File(SECTIONS_DIR).listFiles(object : FilenameFilter {
override fun accept(dir: File?, filename: String): Boolean {
if (filename.matches(regex))
return true
else
return false
}
})
I'm not certain about the Kotlin syntax, but you can certainly trim it down by returning the boolean expression directly, eliminating the if
:
val files = File(SECTIONS_DIR).listFiles(object : FilenameFilter {
override fun accept(dir: File?, filename: String): Boolean {
return filename.matches(regex)
}
})
I believe the Kotlin lambda syntax would look like this:
val files = File(SECTIONS_DIR).listFiles { dir, filename -> filename.matches(regex) }
Edit: removed unnecessary parentheses based on feedback from Sergey Mashkov. Thanks!
To clarify the shortest form:
val files = File(SECTIONS_DIR).listFiles { dir, filename -> filename.matches(regex) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With