我需要编写一个对 Seq[T] 对象执行排序的通用代码.我知道在我们知道基类及其属性之前,不可能执行排序操作.在查看此 answer 后,我接受了此代码,我的要求是处理为尽可能多的自定义数据类型.
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)) 在这里我得到错误,因为 sortWith 函数只需要 Country类型而不是 T 类型.
input.sortWith(sortingMap(criteria)) here I get error as sortWith function only takes Country type and not T type.
推荐答案如果您想使用 sortWith 定义排序,这里有一个方法:
Here's an approach if you want to define your ordering using 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))更多推荐
对通用对象列表进行排序
发布评论