![]() ![]() ![]() In contrast, the reduce() function doesn’t take an initial value, and instead uses the first and second elements of the collection as parameters during the first invocation of the lambda. The fold() function takes an initial value, and the first invocation of the lambda will receive that initial value and the first element of the collection as parameters. The difference between the two functions is simple. The two arguments that these functions require are the accumulated value and the element of the collection. The fold() and reduce() functions can be used to apply operations sequentially on a collection of elements and return the accumulated result. To be more specific, we can use the sumOf() extension function with Int, Long, Double, UInt, ULong, BigInteger, and BigDecimal data types. So, there’s no need to have functions with different names for each data type, just like sumBy() and sumByDouble(). Despite that, we can also use this function with a list of Byte, Short, Long, and Float elements: val sumBy = numbers.sumBy )Īs shown above, we can use the same function to sum Int and UInt values and return Int and UInt summations, respectively. This function always returns an integer value. We can use the sumBy() function to find the sum of all values that are mapped by applying the selector function to each element in the collection. ![]()
0 Comments
Leave a Reply. |