Skip to content

Instantly share code, notes, and snippets.

@Farhandroid
Last active March 22, 2022 09:19
Show Gist options
  • Save Farhandroid/e25426a5c5c650ab7ea4d17603f5be22 to your computer and use it in GitHub Desktop.
Save Farhandroid/e25426a5c5c650ab7ea4d17603f5be22 to your computer and use it in GitHub Desktop.
SearchGeneric
data class Person(val name: String, val email: String, val age: Int)
fun search() {
val henry = Person(name = "Henry", email = "[email protected]", age = 24)
val robert = Person(name = "Robert", email = "[email protected]", age = 22)
val tom = Person(name = "Tom", email = "[email protected]", age = 25)
val listOfPerson = listOf(henry, robert, tom)
val searchUtil = SearchUtil(list = listOfPerson)
searchUtil.searchItem(element = henry) {
println("Search result : $it")
}
}
class SearchUtil<T>(private val list: List<T>) {
fun searchItem(element: T, foundItem: (element: T?) -> Unit) {
val itemFoundList = list.filter {
it == element
}
if (itemFoundList.isNullOrEmpty()) foundItem(null) else
foundItem(itemFoundList.first())
}
}
fun main() {
search()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment