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 if
–else
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
Post a Comment