1

I am new to Scala, below are three function declarations that are confusing to me:

First

scala> def sum = (a: Int, b: Int) => a + b
sum: (Int, Int) => Int

Second

scala> def sum (a: Int, b: Int) = a + b
sum: (a: Int, b: Int)Int

Third

scala> val sum = (a: Int, b: Int) => a + b
sum: (Int, Int) => Int = <function2>

I know that the second one is method, third one is a function literal. My confusion is with the first declaration, is it a normal function or is it a some other syntax that I do not understand? An explanation would be appreciated.

EDIT

Also, when I try to create a partially applied function using the first declaration I get this:

scala> val anotherSum = sum _
anotherSum: () => (Int, Int) => Int = <function0>

Which I expected to be of type Function2 as sum has 2 parameters.

justAbit
  • 4,226
  • 2
  • 19
  • 34
  • Hope this helps: http://www.tutorialspoint.com/scala/scala_closures.htm . Dig around scala closures ,, – Pavel Apr 12 '16 at 08:22
  • "I know that the second one is a normal function" – No, the second one is a method, not a function. The first one is also a method (albeit one that returns a function). Only the third one is a function. – Jörg W Mittag Apr 12 '16 at 11:28
  • @JörgWMittag thanks, I have updated my question. – justAbit Apr 12 '16 at 12:13

1 Answers1

3

The first and second declarations declare different things. It's not the same thing with different syntax.

scala> def sum = (a: Int, b: Int) => a + b
sum: (Int, Int) => Int

Here, you define a method named sum that takes no parameters and returns a function that takes two Int parameters and returns an Int.

So, sum is a method that returns a function that adds two numbers.

scala> def sum (a: Int, b: Int) = a + b
sum: (a: Int, b: Int)Int

Here, you define a method named sum that takes two Int parameters and that returns an Int.

So, sum is a method that adds two numbers.

The difference is that in the first version, sum takes no parameters and returns a function, and in the second, sum takes two parameters and returns an Int. Two very different things!

The third:

scala> val sum = (a: Int, b: Int) => a + b
sum: (Int, Int) => Int = <function2>

Here you define a value named sum that is a Function2, in other words, a function that takes two Int parameters and returns an Int.

So, sum is a value that is of type Function2, and refers to a function that adds two numbers.

Extra:

scala> val anotherSum = sum _
anotherSum: () => (Int, Int) => Int = <function0>

Look carefully at the type. anotherSum is a function that takes no parameters that returns a function that takes two Int parameters that returns an Int.

You are not partially applying anything here. Section 6.7 Method Values of the Scala Language Specification explains what happens here.

Jesper
  • 202,709
  • 46
  • 318
  • 350