1

In scala, a named function is defined as:

scala> def addOne(x: Int): Int = x+1
addOne: (x: Int)Int

scala> :type addOne
(x: Int)Int

And an anonymous one as:

scala> val addOne = (x:Int) => x+1
addOne: Int => Int = <function1>

scala> :type addOne
Int => Int

Why do their types look different?

Why can't a named function be passed as an argument to another function?

Shouldn't both be treated uniformly from type and first-order behavior point of views?

Niket Kumar
  • 495
  • 3
  • 11

1 Answers1

4

def addOne(x: Int): Int is not a function in scala. It's a method of some object.

Functions like val addOne = (x:Int) => x+1 are objects of type FunctionN (in this case Function1) with method apply.

One can use method as function in scala - compiler can create a function from method, for instance:

scala> List(1, 2, 3).map((1).+) // or just `1+`
res0: List[Int] = List(2, 3, 4)

In this case method + of object 1 is used as function x => (1).+(x).

scala> List(1, 2, 3).foreach(println)
1
2
3

Method println of object Predef is used as function s => Predef.println(s).

Since version 2.10 you can't use :type on methods:

scala> def addOne(x: Int): Int = x+1
addOne: (x: Int)Int

scala> :type addOne
<console>:9: error: missing arguments for method addOne;
follow this method with `_' if you want to treat it as a partially applied function
       addOne
       ^
senia
  • 37,745
  • 4
  • 88
  • 129