Bird Operator in Scala – Pretty method chain

Bird Operator in Scala – Pretty method chain

Introduction

Since now know how to use Scala Methods, today we are going to talk about how to chain methods together in a pretty way: the Bird Operator.

What is it?

The bird operator or arrow or combination or andThen, whatever you want to call it, is to chain methods.

Instead of:

f(g(h(x)))

which is really annoying to read, the bird operator allow you to write it that way:

x |> h |> g |> f

It is much easier to read, you can follow how the value it transformed in the left to right reading direction.

Also if you are using a font which support ligature such as Fire Code (that I LOVE and use everywhere), it will looks even better.

Bird operator with Fire Code
Bird operator with Fire Code

How to add it to your project in Scala?

There is an amazing article about it Bird Operator by Nicolas A Perez.

object BirdOperator extends Serializable {
    implicit class Pipe[A](a: A) {
        def |>[Z](f: A => Z): Z = f(a)
    }

    implicit class Pipe2[A, B](a: (A, B)) {
        def |>[Z](f: (A, B) => Z): Z = f.tupled(a)
    }
}

to import:

import BirdOperator._

Play with it!

Give a try with Scastie:

Or if it does not work in your browser, just go directly there.

Bird Operator with partially-applied functions

There are some cases where you would like to use a method where only one of the parameters are part of the pipeline. In those case you will have to use this syntax:

??? |> (function(value, _)) |> ???

As you can see you put the _ wildcard placeholder where you want the pipeline to continue and you need the extra outer parentheses.

In practice:

Or directly on Scastie.

Scala 2.13

As xicmiah pointed out on Reddit, the pipe function is part of the standard library in scala 2.13.

But if, like me you are using 2.11 or 2.12 then you can still use what you have learned in this article.

Conclusion

You can now make your code looks awesome with the Bird Operator in Scala !

2 thoughts on “Bird Operator in Scala – Pretty method chain”

  1. A small correction: you’re talking about *partially-applied functions*. *Partial functions* in Scala are a whole other beast.

Leave a Reply

%d bloggers like this: