Skip to content

Instantly share code, notes, and snippets.

@magdamiu
Created December 12, 2021 12:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save magdamiu/89a73b698d1c03f803a908a45c539e70 to your computer and use it in GitHub Desktop.
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