For example
case class Blah(security: String, price: Double) val myList = List(Blah("a", 2.0), Blah("b", 4.0)) val sum = myList.sum(_.price) // does not work
What is the syntax for obtaining the sum?
Scala List sum() method with example. The sum() method is utilized to add all the elements of the stated list. Return Type: It returns the sum of all the elements of the list.
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.
Try this:
val sum = myList.map(_.price).sum
Or alternately:
val sum = myList.foldLeft(0.0)(_ + _.price)
You appear to be trying to use this method:
def sum [B >: A] (implicit num: Numeric[B]): B
and the compiler can't figure out how the function you're providing is an instance of Numeric
, because it isn't.
Scalaz has this method under a name foldMap
. The signature is:
def M[A].foldMap[B](f: A => B)(implicit f: Foldable[M], m: Monoid[B]): B
Usage:
scala> case class Blah(security: String, price: Double) defined class Blah scala> val myList = List(Blah("a", 2.0), Blah("b", 4.0)) myList: List[Blah] = List(Blah(a,2.0), Blah(b,4.0)) scala> myList.foldMap(_.price) res11: Double = 6.0
B
here doesn't have to be a numeric type. It can be any monoid. Example:
scala> myList.foldMap(_.security) res12: String = ab
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With