Skip to content

Instantly share code, notes, and snippets.

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) ="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
// 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) }
and ::authorStartsWithB
and ::lengthOfTitleGraterThan5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment