S. Pauk
S. Pauk

Reputation: 5318

Is it possible to use functional interface in collection filtering in Kotlin?

The following code compiles:

val collection = listOf("a", "b")
val filter = { x: String -> x.isEmpty() }
collection.filter(filter)

Is it possible to define the filter using a function interface?

For example the following code doesn't compile:

fun interface MyFilter {
    fun execute(string: String): Boolean
}

and

val filter = MyFilter { x -> x.isEmpty() }

gives a compilation error

Type mismatch.
Required:
(TypeVariable(T)) → Boolean
Found:
MyFilter

Upvotes: 1

Views: 290

Answers (2)

IR42
IR42

Reputation: 9672

You can inherit MyFilter from (String) -> Boolean

fun interface MyFilter : (String) -> Boolean

fun main() {
    val collection = listOf("a", "b")
    val filter = MyFilter { x -> x.isEmpty() }
    val newCollection = collection.filter(filter)
}

With your custom method:

fun interface MyFilter : (String) -> Boolean {
    override operator fun invoke(p1: String): Boolean = execute(p1)
    fun execute(param: String): Boolean
}

But it works only with jvmTarget = 1.8 (or higher) and -Xjvm-default=all

Upvotes: 3

Sergio
Sergio

Reputation: 30645

You can use member reference operator :: to pass the function of interface by reference:

val collection = listOf("a", "b")
val filter = MyFilter { x -> x.isEmpty() }
collection.filter(filter::execute)

fun interface MyFilter {
    fun execute(string: String): Boolean
}

Upvotes: 1

Related Questions