computereasy computereasy - 16 days ago 6
Scala Question

Scalaz pipe operator connected with a list method

I am a newbie to

Scala
, but I have some experience in using
OCaml
. I am thinking to adopt the pipe operator defined in
Scalaz
in the following way:

import scalaz._
import Scalaz._

def test = {
def length2(x:String) = List(x.length * 2)
"asdasd" |> length2
}


The above code works fine. However, when I want to bridge another function to get the length of the
list
, it throws an compilation error:

def test = {
def length2(x:String) = List(x.length * 2)
"asdasd" |> length2
.length <======== I cannot do this...
}


Besides, can I put the
|>
operator in another line? like this?

def test = {
def length2(x:String) = List(x.length * 2)
"asdasd"
|> length2 <====== I cannot do this...
}


Currently, I have no idea how to do the above two things in
Scala
. I am really sorry if this question is too naive.. But could anyone tell me whether it is feasible in
Scala
? Thank you!

Answer

You need to pass the "thrush" combinator a function, so the following works:

"asdf" |> length2 |> (_.length)

If you want to insert line breaks, put the operator at the end of the line:

"asdf" |>
length2 |>
(_.length)
Comments