list 的类型是List[Int]。所以,list.map(...) 的参数必须是从Int 到某个东西的函数。
您似乎试图用List(_+1) 创建的是一个从整数到恰好有一个元素的整数的函数列表:后继函数。
它无法编译,因为这是 Scala 编译器无法推断表达式类型的情况之一。但实际上,List[_] 是从Int 到某事的有效函数:
val f = List(99, 88, 77)
f(1) // -> 88
所以要编译你的代码,你必须给编译器一点提示,以便它进行类型检查:
val list = List(1, 2, 3, 4)
list.map(List[Function[Int, Int]](_ + 1))
// ^^^^^^^^^^^^^^^^^^^^ type annotation
这也是有效的:
list.map(List[Int => Int]](_ + 1))
它会编译,但在运行时会失败,因为您正在尝试获取单元素列表的元素 1、2、3 和 4。如果列表只包含零(该特定列表的唯一有效索引),它会起作用:
val list = List(0, 0, 0)
list.map(List[Function[Int, Int]](_ + 1))
// -> evaluates to a list of three functions
...或者如果函数列表包含足够的元素以使索引 1、2、3 和 4 存在:
val list = List(1, 2, 3, 4)
list.map(List[Function[Int, Int]]( // a list of 5 functions:
_ + 1, // 0) the successor function,
_ * 10, // 1) the "append a zero" function,
Math.abs, // 2) the absolute value function,
_ / 2, // 3) the half function
x => 2 // 4) the constant function with value 2
))
// -> evaluates to a list of four functions. Can you guess which ones?