What does the _ parameter mean in this context?

What does the "_" parameter mean in the bottom method call?

Is this a template that accepts a parameter of any type?

val integerSorter = msort[Int]((a, b) => a < b) _ 

Msort signature method:

  def msort[T](less: (T, T) => Boolean)(xs: List[T]): List[T] = { 
+6
source share
2 answers

The easiest way to explain this is probably for the compiler to complete most of the explanations - just try the first line without underscore:

 scala> val integerSorter = msort[Int]((a, b) => a < b) <console>:11: error: missing arguments for method msort; follow this method with `_' if you want to treat it as a partially applied function val integerSorter = msort[Int]((a, b) => a < b) ^ 

So, you have the msort method has two parameter lists, but you just passed the arguments for the first, and the final underscore is the syntax that Scala provides to tell the compiler that you want partially the application in this situation.

(If you try this line in REPL with underscore, you will see that the output type of integerSorter is List[Int] => List[Int] , so to answer your second question, no, underscore does not allow you to specify a parameter of any type. )

For more information, see section 6.7 language specification :

The expression e _ well-formed if e is of a method type or if e is a call-by-name. If e is a method with parameters, e _ represents e converted to a function type by means of the eta extension (ยง6.26.5).

Reading the eta extension section may also be helpful.

+10
source

msort accepts two parameters, a function that returns a boolean, and a list of items to sort. the integerSorter function provides the first parameter, and the underscore represents the list that still needs to be specified. look at currying ( http://www.scala-lang.org/old/node/135.html ) for a more detailed explanation.

+2
source

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


All Articles