list - Sort depending on variable in Scala -


is there way in scala sort list of objects specific field using variable set order (asc or desc)?

i know sortwith can like

mylist.sortwith((x, y) => x < y)  

or

mylist.sortwith((x, y) => x > y)  

to sort ascending or descending, want use variable.

so, tried this:

case class person(firstname: string, lastname: string, age: int)  private def sortdocuments(sortfield: string, sortdirection: string, people: list[person]): list[person] = {   sortfield match {     case "age" => people.sortby(if (sortdirection == "desc") -_.age else _.age)     case "firstname" => people.sortwith { sortstring(a.firstname, b.firstname, sortdirection) }     case "lastname" => people.sortwith { sortstring(a.firstname, b.lastname, sortdirection) }   } }  private def sortstring(fielda: string = null, fieldb: string = null, direction: string = "asc") = {   val fieldavaild = option(fielda).getorelse("")   val fieldbvaild = option(fieldb).getorelse("")   if (direction == "desc") fieldbvaild > fieldavaild else fieldavaild < fieldbvaild } 

but sortwith receives function 2 parameters, error when add third parameter (sortdirection).

you forgot (a, b) => expr part of first/last name cases

case "firstname" => people.sortwith {(a, b) => sortstring(a.firstname, b.firstname, sortdirection) } 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -