# Sorting lists by various measures of goodness [closed]

 def sort[A, B: Ordering](data: List[A], desc: Boolean)(measure: A => B): List[A] = {
val baseOrdering = Ordering.by(measure)
val ordering = if (desc) baseOrdering.reverse else baseOrdering
data.sorted(ordering)
}

private def sortOne(stats: List[One], by: String, desc: Boolean): List[One] =
by match {
case "good" => sort(stats, desc)(_.data.good)
case "gross" => sort(stats, desc)(_.data.gross)
case "warn" => sort(stats, desc)(_.data.warn)
case "exuberant" => sort(stats, desc)(_.data.exuberant)
case other => stats
}
private def sortTwo(stats: List[Two], by: String, desc: Boolean): List[Two] =
by match {
case "good" => sort(stats, desc)(_.data.good)
case "gross" => sort(stats, desc)(_.data.gross)
case "warn" => sort(stats, desc)(_.data.warn)
case "exuberant" => sort(stats, desc)(_.data.exuberant)
case other => stats
}

private def sortThird(stats: List[Third], by: String, desc: Boolean): List[Third] =
by match {
case "good" => sort(stats, desc)(_.data.good)
case "gross" => sort(stats, desc)(_.data.gross)
case "warn" => sort(stats, desc)(_.data.warn)
case "exuberant" => sort(stats, desc)(_.data.exuberant)
case other => stats
}


Actually there are more classes. They all have same fields like good, gross, bad, warn.

These classes that are in methods have all similar fields good, gross, bad, warn. I can't rewrite classes.

It is working, but it looks bad. Maybe someone has some ideas?

• Assuming the fields are numeric, you can get rid of the desc match by doing data.sortBy ( if desc _.good else - _.good ) stackoverflow.com/a/7803042/14955 May 27, 2016 at 12:43
• Welcome to Code Review. This is a fine question, but you could add a small description of what this code is doing and what you want as a review. May 27, 2016 at 13:57
• This is a borderline question for Code Review. One, Two, and Third look like fake placeholders for some class names. What are the real classes, and what do they look like? Please tell us so that we can advise you properly. May 27, 2016 at 16:49

You could try that:

def sort[A, B: Ordering](data: List[A], desc: Boolean)(measure: A => B): List[A] = {
val baseOrdering = Ordering.by(measure)
val ordering = if (desc) baseOrdering.reverse else baseOrdering
data.sorted(ordering)
}


Then you do

sort(listOfFirstClass, desc)(_.good)