Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
High-order functions | High performance with idiomatic Kotlin
fun titleStartsWithS(book: Book) = book.title.startsWith("S")
fun lengthOfTitleGraterThan5(book: Book) = book.title.length > 5
fun authorStartsWithB(book: Book) = book.author.startsWith("B")
val book1 = Book("Start with why", "Simon Sinek")
val book2 = Book("Dare to lead", "Brene Brown")
val books = listOf(book1, book2)
// this code should be improved
val filteredBooks = books
.filter(::titleStartsWithS)
.filter(::authorStartsWithB)
.filter(::lengthOfTitleGraterThan5)
// 1st solution = dedicated predicat
fun allFilters(book: Book): Boolean = titleStartsWithS(book)
&& lengthOfTitleGraterThan5(book)
&& authorStartsWithB(book)
// 2nd solution = anonymous function
books.filter(fun(book: Book) = titleStartsWithS(book)
&& lengthOfTitleGraterThan5(book)
&& authorStartsWithB(book))
// 3rd solution = function composition
inline infix fun <P> ((P) -> Boolean).and(crossinline predicate: (P) -> Boolean): (P) -> Boolean {
return { p: P -> this(p) && predicate(p) }
}
books.filter(
::titleStartsWithS
and ::authorStartsWithB
and ::lengthOfTitleGraterThan5
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment