In this code I'm attempting to double each value and then sum v :
case class s(v : Int)
val l = List(s(2) , s(3))
l.fold(0) ((_.v * 2) + (_.v * 2))
But I receive error :
value v is not a member of Any
How can I perform an operation on each attribute of the object within the List?
As the other authors also noted, fold expects the accumulator of the supertype for your class. The class itself is also a supertype for itself, so we can write
case class s(v : Int)
val l = List(s(2) , s(3))
l.fold(s(0)){case (acc, elem) => s((acc.v * 2) + (elem.v * 2))}.v
but that indeed feels too heavy. in this case the simple:
l.map(_.v*2).sum
would do better.
The first element in the fold is the starting element and you are calling 0.v, also note the fold signature is def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1, that means that it returns a variable of a type which is a super type of the passed type parameter, use foldLeft instead which allows you to build a value which is a subtype:
l.foldLeft(0) ((acc, curr) => acc + (curr.v * 2))
I used acc and curr to better visualize what was happening inside the fold, this is the abbreviated form:
l.foldLeft(0) (_ + _.v * 2)
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