Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How do I define an anonymous function with a variable argument list?

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
                          ^
like image 235
Martin C. Martin Avatar asked Jul 07 '10 12:07

Martin C. Martin


People also ask

How do you declare anonymous function in scala?

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.

Can you assign a anonymous function to a variable?

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.

Do anonymous functions receive arguments?

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.

Can you assign an anonymous function to a variable and pass it as an argument to another function in JavaScript?

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.


1 Answers

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
like image 181
michael.kebe Avatar answered Oct 11 '22 08:10

michael.kebe