Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the _ parameter signify in this context?

Tags:

scala

What is the parameter "_" in below method call signify ?

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

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

The method msort signature :

  def msort[T](less: (T, T) => Boolean)(xs: List[T]): List[T] = {
like image 865
blue-sky Avatar asked May 25 '14 19:05

blue-sky


1 Answers

The easiest way to explain this is probably to let the compiler do most of the explaining—just try the first line without the 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 there you have it—the msort method has two parameter lists, but you've only passed arguments for the first, and the trailing underscore is the syntax that Scala provides to tell the compiler that you want partial application in that situation.

(If you try that line in the REPL with the underscore, you'll see that the inferred type of integerSorter is List[Int] => List[Int], so to answer your second question, no, the underscore doesn't allow you to provide a parameter of any type.)

For more information, see section 6.7 of the language specification:

The expression e _ is well-formed if e is of method type or if e is a call-by-name parameter. If e is a method with parameters, e _ represents e converted to a function type by eta expansion (§6.26.5).

Reading the section on eta expansion may also be helpful.

like image 73
Travis Brown Avatar answered Sep 24 '22 02:09

Travis Brown