Why are types of a named function different from an anonymous one in scala [duplicate]

StackOverflow https://stackoverflow.com/questions/17481663

  •  02-06-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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
       ^
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top