2

When I'm reading source code of some Scala App, I always see such expression val sortedWithId = scores.data.zipWithIndex.sortBy(-_._1).

What does -_ mean?

You know it's so hard to google this kind of expression, so if anyone knows, could you give me some examples?

Thanks in advance.

Phil
  • 153
  • 2
  • 8

1 Answers1

3

There are actually 3 parts in -_._1

  • The minus sign '-' which changes the sign of _._1 (see Jörg comment below for all details)
  • The placeholder parameter for the anonymous function _, writing _._1 is the same as writing x => x._1
  • The access to the first element of the tuple passed as parameter _1

-_._1 is actually passing an anonymous function that returns the negative of the first element of the tuple passed as parameter, and could otherwise be written: w => - w._1

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101
  • Thanks so much! The first - simply means negative, that confused me. – Phil Jun 01 '17 at 05:15
  • 1
    Actually, the first `-` is the unary prefix `-` operator, which is simply syntactic sugar for the `unary_-` method, and since it is just a method like any other method, it can do anything it wants to. `Int.unary_-`, `Long.unary_-` etc. perform negation, but there is nothing which says that every class in the universe must do so. For example, I can imagine an internal DSL for constructing shell commands to overload it in such a way that you can write stuff like `foo -bar, -baz` or something like that. – Jörg W Mittag Jun 01 '17 at 07:46
  • @JörgWMittag Thanks for the precision – Bruno Grieder Jun 01 '17 at 08:16