- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Adding Numbers together
Sat, 2011-06-18, 18:21
Hello,
I have a List[Number]. It contains values of different subclasses of Number - Int, Double, and so on. I want to sum all the values together. If the list only contains Int, I'd like the result to be an Int. If there are mixes, I'd like to follow the normal Scala rules: Int + Double = Double ( and so on ).
list.reduceLeft(_ + _) fails. Number has no + method defined that takes another Number.
How can I do this?
Andrés
I have a List[Number]. It contains values of different subclasses of Number - Int, Double, and so on. I want to sum all the values together. If the list only contains Int, I'd like the result to be an Int. If there are mixes, I'd like to follow the normal Scala rules: Int + Double = Double ( and so on ).
list.reduceLeft(_ + _) fails. Number has no + method defined that takes another Number.
How can I do this?
Andrés