Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

syntax - Error with varargs for function-objects in Scala?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...