Kotlin Higher Order Functions

Working through some back end Firestore code last week, and wanted to create a single query interface to my repository.  The Firestore query interface doesn’t have a single query method, but rather a number of different query methods on a CollectionReference such ‘whereGreaterThan’ or ‘whereEqualTo’.  Each of these CollectionReference query methods have the same signature, which allows for us, in Kotlin to treat this method simply as a parameter to our query.  We simply define a parameter as:

query: CollectionReference.(field: String, value: Any) -> Query

That looks a little complicated, so let me break it down.  We are asking for a method with a receiver type of CollectionReference, that takes 2 parameters, field and value, and return a Query.

fun query(query: CollectionReference.(field: String, value: Any) -> Query, field: String, value: Any): Flux<T> {
   collection.query(field, value).stream(object : ApiStreamObserver<DocumentSnapshot> {....

So now we can call this query method like:

recurringTransactionRepo.query(CollectionReference::whereEqualTo, "sourceType", TransactionSourceType.BANK_ACCT)

Leave a Reply