title: Scala dynamic list sorting
body: <p>I'm looking for a clean way of dynamically sorting a list with the following requirements.</p>
  
  <pre><code>case class Person(name: String, middleName:Option[String], age:Integer) 
  </code></pre>
  
  <p>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?</p>
  
  <p>Thanks in advance</p>
  
  <p>**Updated:</p>
  
  <pre><code>val sortByName = (p :Person) =&gt; p.name
  val sortByMiddleName = (p: Person) =&gt; p.middleName
  
  val mySortMap = Map("name" -&gt; sortByName, "middleName" -&gt; sortByMiddleName)
  
  val sorted = persons.sortBy(mySortMap("name"))
  </code></pre>
  
  <p>** Update #2</p>
  
  <pre><code>import scala.math.Ordering.Implicits._
  
  type PersonSorter = (Person, Person) =&gt; Boolean
  val sortByName: PersonSorter = (x:Person, y:Person) =&gt; x.name &lt; y.name
  // Implicits import takes care of the Option here...
  val sortByMiddleName: PersonSorter = (x:Person, y:Person) =&gt; x.middleName &lt; y.middleName
  
  val sortingMap: PersonSorter = Map[String, PersonSorter]("name" -&gt; sortByName, "middleName" -&gt; sortByMiddleName)
  </code></pre>
  
  <p>(Excluded age, but it's the exact same thing)</p>
  
  <p>Now when I have my list, I can easily just do this.</p>
  
  <pre><code>persons.sortWith(sortingMap("name"))
  </code></pre>
  
  <p>Where "name" is a parameter string passed in from the UI.</p>