我无法理解使用期货的 Scala 身份调用

I am not able to understand Scala identity call using futures

我在摆弄 Predef 身份函数和 Futures 并得到了这个表达式:

identity(_: Future[A])

这个 returns Future[A] => Future[A] 但我只期待 Future[A]

Identity 方法只是 returns 输入,所以我想知道 _: Future[A] 到底是什么意思。

在这种情况下,_: Future[A] 表示一个函数,该函数采用 Future[A] 和 returns 类型的单个参数。

类似于 List(1,2).map(_.toString) 中要映射的参数扩展为 x => x.toString 或采用单个参数并调用 toString 的函数。

在你的例子中,你没有调用任何方法。您只是指定参数的类型(传递函数的类型,而不是身份)所以:

identity(_: Future[A]) 

扩展到

identity((x: Future[A]) => x)

这是一个Future[A] => Future[A]

Predef中的

identity定义如下:

def identity[A](x: A): A = x

如你所见,这是一种方法。当您编写如下内容时:

val f = identity(_: Future[Int])

您正在将方法 identity 转换为 Future[Int] => Future[Int] 类型的函数。 _: Future[Int] 部分称为类型归属,它告诉编译器 identity 的类型 AFuture[Int].

将方法转换为函数的过程称为 eta 扩展。

P.S.: 你可以做同样的事情如下:

val f = identity[Future[Int]] _