def addOne(x: Int): Int
不是 scala 中的函数。这是某个对象的方法。
类似的函数是具有 methodval addOne = (x:Int) => x+1
类型的对象FunctionN
(在这种情况下Function1
)apply
。
可以在 scala 中将方法用作函数 - 编译器可以从方法创建函数,例如:
scala> List(1, 2, 3).map((1).+) // or just `1+`
res0: List[Int] = List(2, 3, 4)
在这种情况下+
,对象的方法1
被用作函数x => (1).+(x)
。
scala> List(1, 2, 3).foreach(println)
1
2
3
println
对象的方法Predef
用作函数s => Predef.println(s)
。
自版本以来2.10
,您不能:type
在方法上使用:
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
^