File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments