Scala sortWith example

The “sortWith” function lets you sort an array according to a specified rule.

To demonstrate this, let’s make a list of random numbers:

val x = 
  List.fill(20)(100)
      .map(scala.util.Random.nextInt)

x: List[Int] = 
  List(90, 13, 69, 46, 66, 
       86, 38, 18, 88, 26, 
       81, 18, 11, 74, 5, 
       50, 7, 42, 74, 57)

You can sort this like so:

x.sortWith(
  (a, b) => {
    a > b
  }
)

Note that you should never use “return” in scala.

The above code can be re-written more simply:

x.sortWith(
  (a, b) =>
    a > b
)

However, “a”, and “b” have no importance here. For simple implementations, you can use an underscore syntax,

x.sortWith(_ > _)

What this does is to create a comparison function that takes two arguments, and checks if the first is larger than the second – in this case the “_” is not a variable, but more of a placeholder syntax.