0

Of course, I could break this code by extracting the list after the filter or the map function and print the size. But for the sake of learning i am wondering whether there is a nicer solution where i could keep this function chaining.

listOfSomething.filter(condition).map(e => e.mapToSomeOther).mkString(DELIMITER)

csmarton
  • 3
  • 1

1 Answers1

0

There is, afaik, no methods on immutable sequences that have side effects, but you can enrich the API with side-effect methods (I don't recommend this) like so:

scala> implicit class PrintSize[T](xs: List[T]){ def printSize = { println(xs.size); xs} }
defined class PrintSize

scala> List(1, 2, 3, 4, 5, 6, 7).filter(_ > 3).printSize.map(_ * 2).mkString(",")
4
res2: String = 8,10,12,14

Your first suggestion about extracting temporary results is much better, because you can do your side effects after or before the entire computation.

Felix
  • 8,385
  • 10
  • 40
  • 59
  • Cool! That's what i was looking for. I extended it a bit so i could alter the filter process and inject the printing part: `implicit class FilterWithLog[T](xs: Set[T]) { def filterEntities(filter: T => Boolean ) = { val filteredEntities = xs.filter(filter) println(s"Number of Entities went down from ${xs.size} to ${filteredEntities.size}") } }` However, it looks like overengineering so yes, i'll stay with the original temporary result extraction solution. It just needed for my learning curve. – csmarton Sep 07 '17 at 06:35