Chaining Operation in Scala 2.13

Scala 2.13 introduced chaining operations using pipe and tap methods. This way we can very easily chain different methods with ease.

Code without pipe and tap:

object Main extends App {
  def deduplicator(base: String) = base + "_" + UUID.randomUUID().toString()
  def timeAttacher(name: String) = name + "_" + System.currentTimeMillis()
  val initValue = "Hello"

  val transformedStr: String = timeAttacher(deduplicator(initValue))
  println(transformedStr)
}

We need to keep wrapping each step or create implicit methods as extensions on the String class.

The pipe method chains methods and tap method execute the method but return the original value. Tap is really helpful in adding logs or other side-effect operations.

But in Scala 2.13, we can use:

import scala.util.chaining._
//use pipe
val pipedStr: String = initValue.pipe(deduplicator).pipe(timeAttacher)
val pipedStr2: String = initValue pipe deduplicator pipe timeAttacher
println(pipedStr)
//use tap
val tappedStr = initValue.pipe(deduplicator).pipe(timeAttacher).tap(v => println("Final value: "+v))