我需要编写对Seq[T]
对象执行排序的通用代码。我知道在知道base class
及其attributes
之前将无法执行排序操作。在研究了此answer之后,我采用了这段代码,我的要求是处理尽可能多的自定义数据类型。
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
)
函数调用
def sort[T]( input : Seq[T], criteria : String) : Seq[T] = {
input.sortWith(sortingMap(criteria))
}
input.sortWith(sortingMap(criteria))在这里出现错误,因为
sortWith
函数仅接受Country
类型,而不接受T
类型。 最佳答案
如果您想使用sortWith
定义顺序,这是一种方法:
case class Country(name: String, id : Int)
type Sorter[T] = (T, T) => Boolean
type CountrySorter = Sorter[Country]
def byName : CountrySorter = (c1, c2) => c1.name < c2.name
def byId : CountrySorter = (c1, c2) => c1.id < c2.id
def sort[T](input: Seq[T], sorter: Sorter[T]): Seq[T] = {
input.sortWith(sorter)
}
val countries = List(Country("Australia", 61), Country("USA", 1), Country("France", 33))
sort(countries, byName)
// res1: Seq[Country] = List(Country(Australia,61), Country(France,33), Country(USA,1))
sort(countries, byId)
// res2: Seq[Country] = List(Country(USA,1), Country(France,33), Country(Australia,61))