gpt4 book ai didi

Scala:什么时候需要函数参数类型?

转载 作者:行者123 更新时间:2023-12-03 20:21:30 25 4
gpt4 key购买 nike

在 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

指向文档的链接的奖励积分。

最佳答案

嗯,有一些极端情况,例如:递归方法必须显式键入,但通常经验法则如下:类型必须来自某个地方。

它们要么来自引用部分:

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 = _ + _

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

关于Scala:什么时候需要函数参数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6929729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com