有一些极端情况,例如:递归方法必须显式类型化,但通常经验法则如下:类型必须来自某个地方。
它们来自参考部分:
val function: (Int, Int) => Int = _ + _
或从对象部分:
val function = (x: Int, y: Int) => x + y
并不重要。 (在 Scala 中!)
我知道你的问题是关于函数的,但这里有一个类似的例子来说明 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)
编辑根据要求,我添加了高阶函数案例。
def higherOrderFunction(firstClassFunction: (Int, Int) => Int) = ...
可以这样调用:
higherOrderFunction(_ + _) // the type of the firstClassFunction is omitted
但是,这不是特例。明确提到了引用的类型。下面的代码说明了一个类似的例子。
var function: (Int, Int) => Int = null
function = _ + _
这大致相当于高阶函数的情况。