Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala placeholder syntax

Tags:

scala

There is something that I can't quite understand hope someone can shed some light.. I have Seq[String]

val strDeps: Seq[String] = ...

and I tried to sort it on the reverse of the 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 sort it without doing a reverse it works fine.

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

Also it works fine without the placeholder syntax

scala> print(strDeps.sortWith((a,b) => a.reverse.compareTo(b.reverse) < 0) mkString ("\n"))
// this works fine too
like image 211
mericano1 Avatar asked Dec 02 '22 01:12

mericano1


1 Answers

_ expands only to the smallest possible scope.

The inner _.reverse part is already interpreted as x => x.reverse therefore the parameter is missing inside sortWith.

like image 71
Debilski Avatar answered Dec 05 '22 06:12

Debilski