According to doc for List
def sorted[B >: A](implicit ord: math.Ordering[B]): List[A]
Sorts this list according to an Ordering.
def sortBy[B](f: (A) ⇒ B)(implicit ord: math.Ordering[B]): List[A]
Sorts this List according to the Ordering which results from transforming an implicitly given Ordering with a transformation function.
When would you use one and when would you use the other? Does one cover a scenario the other does not?
For sortBy you can supply custom function that produces elements used for sorting (e.g. sort by the length string) whereas for sorted you cant:
val xs = List("aa", "b")
// xs: List[String] = List(aa, b)
xs.sortBy{ str => str.length }
// List[String] = List(b, aa)
// now usual lexicographical sorting
xs.sorted
// List[String] = List(aa, b)
xs.sortBy(x => x)
// List[String] = List(aa, b)
xs.sortBy(identity)
// List[String] = List(aa, b)
as you can see, last three lines are identical in their result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With