helpermethod
helpermethod

Reputation: 62294

Why is that anonymous function declaration allowed but this one not?

Why does this work:

val addOne = {a : Int => a + 1 }

But this not:

val addOne = a: Int => a + 1

As far as I understand, both declare an anonymous function with one input parameter.

Upvotes: 1

Views: 155

Answers (2)

tgr
tgr

Reputation: 3608

Because you define a function and assign it to a value.

{ a: Int => a + 1 }

Is a defined function. You can define the function this way as well:

(a: Int) => a + 1

or

(a: Int) => { a + 1 }

It is the same. You just have to wrap the parameterlist with brackets to make it work if you don't want to use paranthese surounding the hole expression.

Upvotes: 4

missingfaktor
missingfaktor

Reputation: 92106

Parameter list has to go in brackets.

val addOne = (a: Int) => a + 1

For full syntax, see the language spec.

Upvotes: 5

Related Questions