2015-01-04 50 views
2

我試圖在列表中斯卡拉像進行乘法運算:我們可以使用list.map調用具有多個參數的方法嗎?

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 

任何想法如何做到這一點?

回答

2
scala> list.map(multiplyListContents(_, multiplier)) 
res0: List[Int] = List(3, 6, 9, 12, 15) 

這意味着list.map(x => multiplyListContents(x, multiplier))
(有關更多信息,請參閱scala placeholder syntax)。

+0

非常感謝.. !! – mkb 2015-01-04 12:38:34

相關問題