I have a requirement to write a generic code that perform sorting on the Seq[T]
objects. I know it won't be possible to perform sorting operation until we know the base class
and its attributes
. After taking a look into this answer I took this code and my requirement is to handle as many custom data type as possible.
case class Country(name: String, id : Int)
type CountrySorter = (Country, Country) => Boolean
def byName : CountrySorter = (c1:Country, c2:Country) => c1.name < c2.name
def byId : CountrySorter = (c1:Country, c2:Country) => (c1.id < c2.id)
val sortingMap = Map[String, CountrySorter](
"sortByCountryName" -> byName ,
"soryByCountryId" -> byId
)
Function call
def sort[T]( input : Seq[T], criteria : String) : Seq[T] = {
input.sortWith(sortingMap(criteria))
}
input.sortWith(sortingMap(criteria)) here I get error as sortWith
function only takes Country
type and not T
type.