Reputation: 1902
In java, you can use implementations of interfaces like this:
import org.springframework.data.mongodb.core.query.Query;
@FunctionalInterface
public interface Filter {
Query apply(Query query);
}
public class FlagFilterFactory {
public Filter create(SearchQuery searchQuery) {
return q -> {
q.addCriteria(...)
return q;
};
}
But I did not find how it can be written using Kotlin.
@FunctionalInterface
public interface Filter {
fun apply(query: Query): Query
}
How can one write an anonymous implementation of this interface? Or do I definitely need to create a class in Kotlin that will implement it?
Upvotes: 1
Views: 669
Reputation: 271355
You can write a fun interface
in Kotlin (no pun intended)
fun interface Filter {
fun apply(query: Query): Query
}
Usage:
fun create(searchQuery: SearchQuery) =
Filter { q ->
q.addCriteria(...)
}
Alternatively, don't declare a new type at all, and just use the function type (Query) -> Query
. (You can make a type alias for this)
typealias Filter = (Query) -> Query
fun create(searchQuery: SearchQuery): Filter = { q ->
q.addCriteria(...)
}
Upvotes: 2