Consider this class:
case class Person(val firstName: String, val lastName: String, age: Int)
val persons = Person("Jane", "Doe", 42) :: Person("John", "Doe", 45) ::
Person("Joe", "Doe", 43) :: Person("Doug", "Don", 65) ::
Person("Darius", "Don", 24) :: Person("Dora", "Don", 20) ::
Person("Dane", "Dons", 29) :: Nil
To get the sum of the age of all persons, I can write code like:
persons.foldLeft(0)(_ + _.age)
But if I want to use sum
, I need to map the value first and the code looks like this:
persons.map(_.age).sum
How can I use the sum
method without creating some intermediate collection?
(I know that such an "optimization" most probably doesn't have any real performance difference when not run in a tight loop and I also know about lazy views and so on.)
Is it possible to have code like
persons.sum(_.age)
doing what foldLeft
/reduceLeft
does?