我需要编写一个对Seq[T]对象执行排序的通用代码。我知道这不会是可能执行排序操作,直到我们知道base class和它的attributes。在查看了这个答案之后,我使用了这段代码,我的要求是处理尽可能多的自定义数据类型。
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
)
Run Code Online (Sandbox Code Playgroud)
函数调用
def sort[T]( input : Seq[T], criteria : String) : Seq[T] = {
input.sortWith(sortingMap(criteria))
}
Run Code Online (Sandbox Code Playgroud)
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
953 次 |
| 最近记录: |