In Scala, how do I define an anonymous function which takes a variable number of arguments?
scala> def foo = (blah:Int*) => 3
<console>:1: error: ')' expected but identifier found.
def foo = (blah:Int*) => 3
^
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.
An anonymous function in javascript is not accessible after its initial creation. Therefore, we need to assign it to a variable, so that we can use its value later. They are always invoked (called) using the variable name. Also, we create anonymous functions in JavaScript, where we want to use functions as values.
The anonymous function accepts one argument, x , and returns the length of its argument, which is then used by the sort() method as the criteria for sorting.
They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
It looks like this is not possible. In the language specification in chapter 6.23 Anonymous functions the syntax does not allow an *
after a type. In chapter 4.6 Function Declarations and Definitions after the type there can be an *
.
What you can do however is this:
scala> def foo(ss: String*) = println(ss.length)
foo: (ss: String*)Unit
scala> val bar = foo _
bar: (String*) => Unit = <function1>
scala> bar("a", "b", "c")
3
scala> bar()
0
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