2

I have requirement where I want sum values of all employee salaries in list

employeeList.foldLeft(java.math.BigDecimal.ZERO) { (accSal,emp) => accSal + getSalary(emp,designation,yearsOfExp) }

Here for each employee I want to call a function getSalary and sum the return values to get salaries of all employees

The above code does not seem to work for me , Keep getting error

Type mismatch expected:String actual:BigDecimal
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
mprad
  • 71
  • 1
  • 5

2 Answers2

5

Alternative to Mario's answer, if getSalary returns a java.math.BigDecimal, and the fold should also return one, instead of a scala.math.BigDecimal.
You can do this:

employeeList.foldLeft(java.math.BigDecimal.ZERO) {
  (accSal, emp) =>
    accSal.add(getSalary(emp,designation,yearsOfExp))
}

You can check the javadoc to confirm that they do not have a + method, but an add one.
And for that reason, it was calling the + method that returns Strings.

4

Try scala.BigDecimal(0) instead of java.math.BigDecimal.ZERO, perhaps something like so

employeeList.foldLeft(BigDecimal(0)) { (accSal, emp) => accSal + getSalary(emp) }
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
  • Hi @Mario , I upvoted your answer and accepted Luis answer as the correct answer , As i had to keep the return type as java.math.BigDecimal – mprad Sep 29 '19 at 17:20