Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with varargs for function-objects in Scala?

Tags:

Why does this not work?

val f = (args: Int*) => args.sum

error: ')' expected but identifier found.
val f = (args: Int*) => args.sum
                  ^

This however works perfectly fine

def sum(args: Int*) = args.sum
val f = sum _

so does this

val f: (Int*) => Int = args => args.sum

btw. I'm using scala 2.9.1

like image 904
SpiderPig Avatar asked Dec 24 '11 06:12

SpiderPig


1 Answers

I'm not an expert in specification reading, but it looks like the varargs Syntax is not supported for anonymous function.

Compare the syntax for Function Declaration vs Anonymous Functions in the Language Spec

From 4.6 Function Declarations and Definitions

ParamType ::= Type
              | ‘=>’ Type
              | Type ‘*’

6.23 Anonymous Functions

Binding ::= (id | ‘_’) [‘:’ Type]

I have no idea what the reasons for that though. There seem to be reasons but none that can easily be explained. Martin Odersky commented on a request to add varargs for anonymous functions: "This looks tempting at first, but it would drag in a lot of complexity (you just need to believe me on that one)."

like image 130
Jens Schauder Avatar answered Oct 08 '22 05:10

Jens Schauder