Skip to content

Instantly share code, notes, and snippets.

@diefferson
Created March 11, 2022 13:38
Show Gist options
  • Save diefferson/e861e33dfb165723ab60ae01d7f85e75 to your computer and use it in GitHub Desktop.
Save diefferson/e861e33dfb165723ab60ae01d7f85e75 to your computer and use it in GitHub Desktop.
Generic sort by field
package br.com.juno.domain.utils
data class Item (val id:Int, val name: String)
enum class ItemSortBy {
ID,
NAME
}
fun List<Item>.sortByField(field: ItemSortBy): List<Item> {
return this.sortedBy {
when(field){
ItemSortBy.ID-> it.id as Comparable<Any>
ItemSortBy.NAME-> it.name as Comparable<Any>
}
}
}
fun sortItems(items: List<Item>, sortBy: ItemSortBy): List<Item> {
return items.sortByField(sortBy)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment