Scala - 在映射函数中与 lambda 混淆

我正在学习 Scala 并在命令行中进行试验。我无法理解为什么第二行无法编译。有人可以解释一下吗。

val list = List(1,2,3,4)
list.map(_+1)           //This works. List(2,3,4,5)
list.map(List(_+1))     //But, Compilation Fails here
list.map(x=>List(x+1))  //This works. List(List(2),List(3),List(4),List(5))

谢谢。

最佳答案

Scala 会将 _(在占位符位置使用时)扩展为 x => x,除非这种扩展会导致恒等函数(更多信息请参见这个答案的结尾):

list.map(_+1)       // same as list.map(x => x + 1)       (1)
list.map(List(_+1)) // same as list.map(List(x => x+1))   (2)

(1) 的情况下,scala 可以推断出 x 的类型为 Int(因为 list: List[Int ]).
但是 (2) 失败了

error: missing parameter type for expanded function ((x$1) => x$1.$plus(1))

因为 scala 无法推断 xList(x => x+1) 中的类型。


关于扩展和恒等函数:

scala> list.map(List(_))
res3: List[List[Int]] = List(List(1), List(2), List(3), List(4))

有效,因为 list.map(List(x => x)) 扩展被拒绝,下一个可能的是 list.map(x => List(x) ),它给出 res3

https://stackoverflow.com/questions/38615221/

相关文章:

r - 组的总和,但对 r 中的每一行保持相同的值

validation - 删除 Rails 5 上 belong_to 属性所需的验证

node.js - 应用程序使用(验证器()); ^ 类型错误 : validator is not

api - 交响乐 2 : How to use the ParamConverter with a

python - 从 Tkinter Tcl 回调到 python 函数在 Windows 中崩溃

ruby-on-rails - 是否可以清除 Spring gem 的缓存?

php - 如何检查字符串是否包含电子邮件?

python - 将变量注入(inject)导入命名空间

rx-java - 在 RxJava 中将 Observable 转换为 Collection

c - ArduinoJSON 未定义对 `__cxa_guard_acquire' 的引用