我试图在Scala中对列表执行乘法运算,如:
val list = List(1,2,3,4,5)
list.map(_*2)
res0: List[Int] = List(2, 4, 6, 8, 10) // Output
现在,我为乘法操作创建了一个单独的方法,如:
val list = List(1,2,3,4,5)
def multiplyListContents(x: Int) = {
x * 2
}
list.map(multiplyListContents)
res1: List[Int] = List(2, 4, 6, 8, 10) // Output
现在我想传递自定义乘数而不是使用默认乘数2
,如:
val list = List(1,2,3,4,5)
val multiplier = 3
def multiplyListContents(x: Int, multiplier: Int) = {
x * multiplier
}
list.map(multiplyListContents(multiplier))
res1: List[Int] = List(3, 6, 9, 12, 15) // Output should be this
知道怎么做吗?
答案 0 :(得分:2)
scala> list.map(multiplyListContents(_, multiplier))
res0: List[Int] = List(3, 6, 9, 12, 15)
这转换为list.map(x => multiplyListContents(x, multiplier))
(有关详细信息,请参阅scala placeholder syntax
。)