Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
            }
        })
like image 713
ZakTaccardi Avatar asked Dec 01 '22 14:12

ZakTaccardi


2 Answers

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!

like image 160
David Conrad Avatar answered Dec 08 '22 06:12

David Conrad


To clarify the shortest form:

val files = File(SECTIONS_DIR).listFiles { dir, filename -> filename.matches(regex) }
like image 23
Jayson Minard Avatar answered Dec 08 '22 06:12

Jayson Minard