scala pipe operator |>
Code

Scala pipe operator „|>”

Scala pipe operator „|>” passes the result of the left side to the right side method/function as the first argument. t is, one might argue, „yet another arrow”, that provides „something” to be put „somewhere”. This is absolutely true but in addition it provides readability.

Scala pipe operator „|>” source code

It is just a simple fancy looking generic function :

 implicit class PipeOperator[A](val value: A) extends AnyVal {  def |>[B](f: A => B): B = f(value)
}

IThis operator shines if Your code at least tries to follow rules written down by Uncle Bobo and his clean code mentality. This allows you to chain function calls in a more natural left-to-right order, which can sometimes be more readable than nested function calls.

Just don`t get overboard with this and do not make one liner methods ALL the time. Use COMMON SENSE 🙂 Which is not that common anymore 🙁 Everyone is bend over hell on patterns and dry… but nevermind.

Where scala pipe operator works best ?

Scala pipe operator works very well in for comprehension block


import cats.implicits._

// Define some sample methods
def double(x: Int): Int = x * 2
def triple(x: Int): Int = x * 3
def square(x: Int): Int = x * x

// Example usage within a for comprehension block
val result = for {
  i <- 1 to 5
  j <- i |> double |> triple |> square |> (_ + 1) // Using the pipe operator to chain function calls
} yield j

println(result) // Output will be Vector(49, 196, 441, 784, 1225)

Piotr Kowalski