sorting - Extending Seq.sortBy in Scala -


say have list of names.

case class name(val first: string, val last: string)  val names = name("c", "b") :: name("b", "a") :: name("a", "b") :: nil 

if want sort list last name (and if not enough, first name), done.

names.sortby(n => (n.last, n.first)) // list[name] = list(name(a,b), name(c,b), name(b,a)) 

but what, if i‘d sort list based on other collation strings?

unfortunately, following not work:

val o  = new ordering[string]{ def compare(x: string, y: string) = collator.compare(x, y) } names.sortby(n => (n.last, n.first))(o) // error: type mismatch; // found   : java.lang.object ordering[string] // required: ordering[(string, string)] //   names.sortby(n => (n.last, n.first))(o) 

is there way allow me change ordering without having write explicit sortwith method multiple ifelse branches in order deal cases?

well, trick:

names.sorted(o.on((n: name) => n.last + n.first)) 

on other hand, can well:

implicit val o  = new ordering[string]{ def compare(x: string, y: string) = collator.compare(x, y) } names.sortby(n => (n.last, n.first)) 

this locally defined implicit take precedence on 1 defined on ordering object.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -