tags:

views:

130

answers:

2

Are these two function declarations effectively different?

If not, why do they have different toString values?

scala> def f: (Int) => Int = x=> x*x
f: (Int) => Int

scala> def f(x: Int) = x*x
f: (Int)Int
+12  A: 

The first is a no-argument method f1 that returns a Function1[Int, Int].

scala> def f1: (Int => Int) = (x: Int) => x * x
f1: (Int) => Int

The second is a one argument method f2 that takes an an Int and returns an Int.

scala> def f2(x: Int): Int = x * x
f2: (x: Int)Int

You can invoke f1 and f2 with the same syntax, although when you call f1(2) it is expanded to f1.apply(2).

scala> f1
res0: (Int) => Int = <function1>

scala> f1(2)
res1: Int = 4

scala> f1.apply(2)
res2: Int = 2

scala> f2(2)
res3: Int = 4

Finally, you can 'lift' the method f2 to a function as follows.

scala> f2
<console>:6: error: missing arguments for method f2 in object $iw;
follow this method with `_' if you want to treat it as a partially applied funct
ion
       f2
       ^

scala> f2 _
res7: (Int) => Int = <function1>

scala> (f2 _).apply(2)
res8: Int = 4

Exercise: What is the type of f1 _?

retronym
A no-arg function, returning a function that maps Int to Int.scala> f1 _res6: () => (Int) => Int = <function>Interestingly we can keep "lifting"...scala> res6 _res7: () => () => (Int) => Int = <function>scala> res7 _res8: () => () => () => (Int) => Int = <function>scala> res8()()()(9)res9: Int = 81Thanks for the info @retronym. The exercise is a nice touch!
Synesso
BTW, the precise term for this conversion in Scala is Eta Expansion. See '6.7 Method Values' and '6.25.5 Eta Expansion' in http://www.scala-lang.org/docu/files/ScalaReference.pdf
retronym
+2  A: 

These are methods declarations, not function declarations. The first method returns a function, the second returns an Int and has nothing to do with functions.

See this question.

Daniel