|
| 1 | +/* |
| 2 | + * Scala (https://www.scala-lang.org) |
| 3 | + * |
| 4 | + * Copyright EPFL and Lightbend, Inc. |
| 5 | + * |
| 6 | + * Licensed under Apache License 2.0 |
| 7 | + * (http://www.apache.org/licenses/LICENSE-2.0). |
| 8 | + * |
| 9 | + * See the NOTICE file distributed with this work for |
| 10 | + * additional information regarding copyright ownership. |
| 11 | + */ |
| 12 | + |
| 13 | +package scala.util |
| 14 | + |
| 15 | +trait ChainingSyntax { |
| 16 | + @`inline` implicit final def scalaUtilChainingOps[A](a: A): ChainingOps[A] = new ChainingOps(a) |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Adds chaining methods `tap` and `pipe` to every type. See [[ChainingOps]]. |
| 21 | + */ |
| 22 | +object chaining extends ChainingSyntax |
| 23 | + |
| 24 | +/** Adds chaining methods `tap` and `pipe` to every type. |
| 25 | + */ |
| 26 | +final class ChainingOps[A](private val self: A) extends AnyVal { |
| 27 | + |
| 28 | + /** Applies `f` to the value for its side effects, and returns the original value. |
| 29 | + * |
| 30 | + * {{{ |
| 31 | + * scala> import scala.util.chaining._ |
| 32 | + * |
| 33 | + * scala> val xs = List(1, 2, 3).tap(ys => println("debug " + ys.toString)) |
| 34 | + * debug List(1, 2, 3) |
| 35 | + * xs: List[Int] = List(1, 2, 3) |
| 36 | + * }}} |
| 37 | + * |
| 38 | + * @param f the function to apply to the value. |
| 39 | + * @tparam U the result type of the function `f`. |
| 40 | + * @return the original value `self`. |
| 41 | + */ |
| 42 | + def tap[U](f: A => U): A = { |
| 43 | + f(self) |
| 44 | + self |
| 45 | + } |
| 46 | + |
| 47 | + /** Converts the value by applying the function `f`. |
| 48 | + * |
| 49 | + * {{{ |
| 50 | + * scala> import scala.util.chaining._ |
| 51 | + * |
| 52 | + * scala> val times6 = (_: Int) * 6 |
| 53 | + * times6: Int => Int = \$\$Lambda\$2023/975629453@17143b3b |
| 54 | + * |
| 55 | + * scala> val i = (1 - 2 - 3).pipe(times6).pipe(scala.math.abs) |
| 56 | + * i: Int = 24 |
| 57 | + * }}} |
| 58 | + * |
| 59 | + * Note: `(1 - 2 - 3).pipe(times6)` may have a small amount of overhead at |
| 60 | + * runtime compared to the equivalent `{ val temp = 1 - 2 - 3; times6(temp) }`. |
| 61 | + * |
| 62 | + * @param f the function to apply to the value. |
| 63 | + * @tparam B the result type of the function `f`. |
| 64 | + * @return a new value resulting from applying the given function |
| 65 | + * `f` to this value. |
| 66 | + */ |
| 67 | + def pipe[B](f: A => B): B = f(self) |
| 68 | +} |
0 commit comments