代码改变世界

scala _ parameter

2018-01-09 17:15  xplorerthik  阅读(157)  评论(0编辑  收藏  举报

Given that sequence, use reduceLeft to determine different properties about the collection. The following example shows how to get the sum of all the elements in the sequence:

scala> a.reduceLeft(_ + _)
res0: Int = 64

Don’t let the underscores throw you for a loop; they just stand for the two parameters that are passed into your function. You can write that code like this, if you prefer:

a.reduceLeft((x,y) => x + y)

The following examples show how to use reduceLeft to get the product of all elements in the sequence, the smallest value in the sequence, and the largest value:

scala> a.reduceLeft(_ * _)
res1: Int = 388800

scala> a.reduceLeft(_ min _)
res2: Int = 2

scala> a.reduceLeft(_ max _)
res3: Int = 20