New Chaining Operations in Scala 2.13

Reading Time: 2 minutes

Scala 2.13 gave us two chaining operations, namely pipe and tap. To call methods one after the other in one go, we use chaining operations.

Pipe

pipe() is used to convert the input value to a new output value formed by applying the function provided to it in the parameter.
Definition : def pipe[B](f: (A) => B) : B
Here, the input value of type A will be converted to B by carrying out the operation f

Example :

def incrementByTwo(num : Int) : Int =
{
    num + 2
}

def decrementByTwo(num : Int) : Int =
{
    num - 2
}

Before pipe(), calling two methods looked like this:

val result = decrementByTwo(incrementByTwo(num))

To chain these methods using pipe(), we do something like this, which is more readable:

import scala.util.chaining._

val num = 25
val result = num.pipe(incrementByTwo).pipe(decrementByTwo)

So, in the above expression, incrementyByTwo is applied on num and then on the result, decrementByTwo is applied.

Note: One should not do computation where we are suppling the input.
E.g – (2 * 2).pipe(incrementByTwo) // 2*2 will cause a little runtime overhead as compared to the following

val four = 2 * 2
val result = incrementByTwo(four)

Tap

tap() is just like pipe() but a little more specific and strict. It takes in a function as a parameter which is side effecting in nature and returns the original value.

Definition: def tap[U](f: (A) => U) : A
Here, the input value of type A will be returned as it is after carrying out the side effecting operation f.

Let’s take the methods defined above incrementByTwo() and decrementByTwo(), and create a new one beautifyResult().

def beautifyResult(result : Int) : Unit =
{
    println(s"Result is: $result")
}

Now, here’s how to use tap()

import scala.util.chaining._

val num = 2
val result = num.pipe(incrementByTwo).pipe(decrementByTwo).tap(beautifyResult)
//Output: Result is: 2
//result = 2

So, result will hold the final value after incrementByTwo and decrementByTwo performed on num. Also, beautifyResult will print the result with a proper message as defined.

Hope this was helpful.
Thanks.

Knoldus-blog-footer-image