Scala placeholder syntax

There is something that I cannot understand that someone can shed light on. I have a Seq [String]

val strDeps: Seq[String] = ... 

and I tried sorting it in reverse using the sortWith method, and I get the following error.

 scala> print(strDeps.sortWith(_.reverse.compareTo(_.reverse) < 0) mkString ("\n")) <console>:15: error: wrong number of parameters; expected = 2 print(strDeps.sortWith(_.reverse.compareTo(_.reverse) < 0) mkString ("\n")) ^ 

But when I try to sort it without doing the opposite, it works fine.

 scala> print(strDeps.sortWith(_.compareTo(_) < 0) mkString ("\n")) // this is fine 

It also works great without placeholder syntax

 scala> print(strDeps.sortWith((a,b) => a.reverse.compareTo(b.reverse) < 0) mkString ("\n")) // this works fine too 
+4
source share
2 answers

_ expands only to the smallest possible area.

The interior of _.reverse already interpreted as x => x.reverse , so the parameter is missing inside sortWith .

+10
source
 compareTo(_) 

It is a partially used method. It just means "compareTo, but without using the first parameter." Note that _ not a parameter. Rather, it indicates the absence of a parameter.

 compareTo(_.reverse) 

Whether the method accepts an anonymous function as a parameter, the _.reverse parameter. This means x => x.reverse .

+8
source

Source: https://habr.com/ru/post/1382930/


All Articles