Is there something like Java Stream's “peek” operation in Scala?

折月煮酒 提交于 2019-12-06 00:02:05

问题


In Java you can call peek(x -> println(x)) on a Stream and it will perform the action for each element and return the original stream, unlike foreach which is Unit. Is there something similar in Scala, ideally something which works on all Monady types, allowing you to "pass through" the original Monad while performing a side effect action? (Logging, e.g.)

It is of course easily implemented:

def tap[A, U](a: A)(action: (A) => U): A = {
  action(a)
  a
}

but I'm hoping for something a bit more elegant or idiomatic.


回答1:


One way to solve this is using implicits:

class Tappable[A](a: A) {
  def tap[U](action: (A) => U): A = {
    action(a)
    a
  }
}

implicit def any2Tappable[A](a: A): Tappable[A] = new Tappable[A](a)

Which can then be used natively:

connection.tap(_.connect()) match {
  case c if c.getResponseCode == 304 => None
  ...

Any other answers?



来源:https://stackoverflow.com/questions/38257367/is-there-something-like-java-streams-peek-operation-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!