Created
December 12, 2021 12:15
Star
You must be signed in to star a gist
High-order functions | High performance with idiomatic Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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