Skip to content
Advertisement

How to use Lambda 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
            }
        })

Advertisement

Answer

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!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement