I'm looking for a clean way of dynamically sorting a list with the following requirements.
case class Person(name: String, middleName:Option[String], age:Integer)
Now sorting that is pretty straight forward however if this sort is driven off a UI where a user would do column sorting and the parameters passed back to the server would simply be the column name. Any suggestions to dynamically create this sorting capability?
Thanks in advance
**Updated:
val sortByName = (p :Person) => p.name
val sortByMiddleName = (p: Person) => p.middleName
val mySortMap = Map("name" -> sortByName, "middleName" -> sortByMiddleName)
val sorted = persons.sortBy(mySortMap("name"))
** Update #2
import scala.math.Ordering.Implicits._
type PersonSorter = (Person, Person) => Boolean
val sortByName: PersonSorter = (x:Person, y:Person) => x.name < y.name
// Implicits import takes care of the Option here...
val sortByMiddleName: PersonSorter = (x:Person, y:Person) => x.middleName < y.middleName
val sortingMap: PersonSorter = Map[String, PersonSorter]("name" -> sortByName, "middleName" -> sortByMiddleName)
(Excluded age, but it's the exact same thing)
Now when I have my list, I can easily just do this.
persons.sortWith(sortingMap("name"))
Where "name" is a parameter string passed in from the UI.