def foo(l: List[Int]) =
List(1,2,3)
.map(_ + 1) // A
.map(x => {println(x);x}) // B
.map(_ + 2) // C
.map(x => {println(x);x}) // D
.map(_ + 3)
The intent is to print or log to a file after step A
and C
and this is one of the implementations. Is this a good practice?
Or break it into multiple temp variables,
def foo(l: List[Int]) = {
val nums = List(1,2,3).map(_ + 1)
nums.foreach(println)
val nums2 = nums.map(_ + 2)
nums2.foreach(println)
nums2.map(_ + 3)
}
Is there any better or straightforward way todo? Thanks
Update 1
Let me further clarify my intent. The idea is to move side effects println(...)
out of map(...)
function but yet I want to print the result along the way. I don't see the need to optimize line B
and D
.