How to add tracing within a 'for' comprehension?

后端 未结 5 1797
离开以前
离开以前 2021-01-30 17:49

For log tracing inside a for comprehension, I\'ve used dummy assignment like this:

val ll = List(List(1,2),List(1))            

for {
  outer <         


        
5条回答
  •  伪装坚强ぢ
    2021-01-30 18:20

    Starting Scala 2.13, the chaining operation tap, has been included in the standard library, and can be used with minimum intrusiveness wherever we need to print some intermediate state of a pipeline:

    import util.chaining._
    
    // val lists = List(List(1, 2), List(1))
    for {
      outer <- lists
      inner <- outer.tap(println)
    } yield inner
    // List(2, 4, 6)
    // List(4, 8, 12)
    // ls: List[Int] = List(4, 8, 12)
    

    The tap chaining operation applies a side effect (in this case println) on a value (in this case the outer list) while returning this value untouched:

    def tap[U](f: (A) => U): A

提交回复
热议问题