Last active
March 22, 2022 09:19
-
-
Save Farhandroid/e25426a5c5c650ab7ea4d17603f5be22 to your computer and use it in GitHub Desktop.
SearchGeneric
This file contains hidden or 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
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