“import scala.util.chaining._” has the “pipe” operator.
Instead of using “pipe” i want to use “|>” like in F#.
So naively i tried.
var |> = pipe.
What is the correct way ?
“import scala.util.chaining._” has the “pipe” operator.
Instead of using “pipe” i want to use “|>” like in F#.
So naively i tried.
var |> = pipe.
What is the correct way ?
scala.util.chaining
’s pipe
is not a zero-cost abstraction; don’t use it for performance-critical hotspots, especially on primitives. (Otherwise you’re fine.)
If you are using Scala 3, the best way to get the F# pipe equivalent is to do it from scratch, like so:
extension [A](a: A)
inline def |>[B](inline f: A => B): B = f(a)
This defines an extension method that works on any type, and what it does is simply apply the specified function. Because the method and function are both inlined, it ends up being exactly as if you had written it out by hand. In particular, if you’ve used a primitive, there’s no boxing.
In Scala 2, you probably want to use the equivalent implicit class
mechanism to add a new method named |>
.
Note that if you use _.foo
syntax to create your functions, it doesn’t work with using pipe
or |>
inline. You need to use parens or braces: 2 |> (_.toString)
or 2 |> { _.toString }
. If you’re just calling an existing method, naming it is fine: 0.7 |> math.cos
. Because of precedence,x => f(x)
needs parens/braces: 2 |> (x => x.toString)
.
Not looking into efficiency the following also worked,
extension[A] (a: A)
@targetName ("|>")
def |>[B](f: A => B): B = a pipe f
Where can i find the “signature” of the pipe operator in the docs ?