Skip to content

Commit ce8db6b

Browse files
authored
Merge pull request scala/scala#7007 from eed3si9n/wip/tap2
Adds tap and pipe
2 parents e9e417c + 98745cf commit ce8db6b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package scala
2+
package util
3+
4+
trait ChainingSyntax {
5+
implicit final def scalaUtilChainingOps[A](a: A): ChainingOps[A] = new ChainingOps(a)
6+
}
7+
8+
/** Adds chaining methods `tap` and `pipe` to every type.
9+
*/
10+
final class ChainingOps[A](val self: A) extends AnyVal {
11+
/** Applies `f` to the value for its side effects, and returns the original value.
12+
*
13+
* {{{
14+
* val xs = List(1, 2, 3)
15+
* .tap(ys => println("debug " + ys.toString))
16+
* // xs == List(1, 2, 3)
17+
* }}}
18+
*
19+
* @param f the function to apply to the value.
20+
* @tparam U the result type of the function `f`.
21+
* @return the original value `self`.
22+
*/
23+
def tap[U](f: A => U): self.type = {
24+
f(self)
25+
self
26+
}
27+
28+
/** Converts the value by applying the function `f`.
29+
*
30+
* {{{
31+
* val times6 = (_: Int) * 6
32+
* val i = (1 - 2 - 3).pipe(times6).pipe(scala.math.abs)
33+
* // i == 24
34+
* }}}
35+
*
36+
* Note: `(1 - 2 - 3).pipe(times6)` may have a small amount of overhead at
37+
* runtime compared to the equivalent `{ val temp = 1 - 2 - 3; times6(temp) }`.
38+
*
39+
* @param f the function to apply to the value.
40+
* @tparam B the result type of the function `f`.
41+
* @return a new value resulting from applying the given function
42+
* `f` to this value.
43+
*/
44+
def pipe[B](f: A => B): B = f(self)
45+
}

library/src/scala/util/package.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package scala
2+
3+
package object util {
4+
/**
5+
* Adds chaining methods `tap` and `pipe` to every type. See [[ChainingOps]].
6+
*/
7+
object chaining extends ChainingSyntax
8+
}

0 commit comments

Comments
 (0)