Scala:何时需要函数参数类型?

Lan*_*uhn 15 scala

在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)

这大致相当于高阶函数情况.

  • 有一个缺失的案例对这个问题非常重要.如果方法需要某种类型的函数,那么您可以省略将函数传递给该方法时的类型. (6认同)

Ben*_*ngs 5

你的第四个例子是一个方法,而不是一个函数(见这个问题).您必须指定方法的参数类型.除非方法是递归的,否则可以推断出方法的返回类型,在这种情况下,必须明确指定它.

  • 方法和功能之间实际差异的简明列表:http://stackoverflow.com/questions/3926047/debunking-scala-myths/4812176#4812176 (2认同)