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] = {
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 ife
is of method type or ife
is a call-by-name parameter. Ife
is a method with parameters,e _
representse
converted to a function type by eta expansion (§6.26.5).
Reading the section on eta expansion may also be helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With