ZakTaccardi ZakTaccardi - 4 years ago 260
Java Question

How to use Lamba expression to make Java method calls less verbose in Kotlin?

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
}
})

Answer Source

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) })

However, I haven't tested this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download