Is there some sort of 'tee' operation on Option
in Scala's standard library available? The best I could find is foreach
, however its return type is Unit
, therefore it cannot be chained.
This is what I am looking for: given an Option
instance, perform some operation with side effects on its value if the option is not empty (Some[A]
), otherwise do nothing; return the option in any case.
I have a custom implementation using an implicit class, but I am wondering whether there is a more common way to do this without implicit conversion:
object OptionExtensions {
implicit class TeeableOption[A](value: Option[A]) {
def tee(action: A => Unit): Option[A] = {
value foreach action
value
}
}
}
Example code:
import OptionExtensions._
val option: Option[Int] = Some(42)
option.tee(println).foreach(println) // will print 42 twice
val another: Option[Int] = None
another.tee(println).foreach(println) // does nothing
Any suggestions?