Entry tags:
2011-02-24
scala solutions
A guy asks a question on a scala forum:
In C# (gasp!) they have this nice feature:
Is there a good way to do this in Scala? E.g. sort my items first by
"foo", if they tie on "foo" then sort them by "bar"?
I end up writing this code:
which gets much worse if you have a third sort key.
and the answer is:
On Thu, Feb 24, 2011 at 3:49 PM, Alex Cruise <alex@******.com> wrote:
Tuples are also comparable in the expected way, so you can also do this:
-0xe1a
In C# (gasp!) they have this nice feature:
items.orderBy( item => item.foo ).thenBy ( item => item.bar )Is there a good way to do this in Scala? E.g. sort my items first by
"foo", if they tie on "foo" then sort them by "bar"?
I end up writing this code:
items.sort { case (item1,item2) =>
if ( item1.foo == item2.foo )
item1.bar > item2.bar
else
item1.foo > item2.foo
}
which gets much worse if you have a third sort key.
and the answer is:
On Thu, Feb 24, 2011 at 3:49 PM, Alex Cruise <alex@******.com> wrote:
Tuples are also comparable in the expected way, so you can also do this:
items sortBy { x => (x.bar, x.foo) }
-0xe1a