在Scala中可以通过多种方式定义函数,这会导致混淆何时需要确切的函数参数类型.我通常从最简单的可能定义开始,然后向下工作直到编译器错误消失.我宁愿真正理解这是如何工作的.
例如:
_ + _
(x, y) => x + y
(x: Int, y: Int) => x + y
def sum(x: Int, y: Int) = x + y // as pointed out, this is a method,
// which not a function
Run Code Online (Sandbox Code Playgroud)
奖励指向文档的链接.
agi*_*eel 17
好吧有一些极端情况如下:递归方法必须明确键入,但通常经验法则如下:类型必须来自某个地方.
它们来自参考部分:
val function: (Int, Int) => Int = _ + _
Run Code Online (Sandbox Code Playgroud)
或者从对象部分:
val function = (x: Int, y: Int) => x + y
Run Code Online (Sandbox Code Playgroud)
没关系.(在斯卡拉!)
我知道你的问题是关于函数,但是这里有一个类似的例子来说明Scala的类型推断:
// no inference
val x: HashMap[String, Int] = new HashMap[String, Int]()
val x: HashMap[String, Int] = new HashMap[String, Int]
// object inference
val x: HashMap[String, Int] = new HashMap()
val x: HashMap[String, Int] = new HashMap
val x: HashMap[String, Int] = HashMap() // factory invocation
// reference inference
val x = new HashMap[String, Int]()
val x = new HashMap[String, Int]
val x = HashMap[String, Int]() // factory invocation
// full inference
val x = HashMap("dog" -> 3)
Run Code Online (Sandbox Code Playgroud)
编辑根据要求我添加了高阶函数案例.
def higherOrderFunction(firstClassFunction: (Int, Int) => Int) = ...
Run Code Online (Sandbox Code Playgroud)
可以像这样调用:
higherOrderFunction(_ + _) // the type of the firstClassFunction is omitted
Run Code Online (Sandbox Code Playgroud)
但是,这不是一个特例.明确提到了引用的类型.以下代码说明了一个类似的示例.
var function: (Int, Int) => Int = null
function = _ + _
Run Code Online (Sandbox Code Playgroud)
这大致相当于高阶函数情况.