Chaining function in Scala using dot notation

前端 未结 2 1771
长情又很酷
长情又很酷 2021-01-06 10:41

So far, the only native method of chaining functions together in Scala I know of is using andThen/compose. It gets the job done but still looks very clunky. For example, if

相关标签:
2条回答
  • 2021-01-06 10:59

    Starting Scala 2.13 you can use the pipe chaining operator:

    import scala.util.chaining._
    
    // def addNumber(i: Int, s: String) = s + i
    // def doubleString(s: String) = (s + s, (s + s).length)
    // def trimString(i: (String, Int)) = i._1.substring(0, i._2-1)
    "Hello".pipe(addNumber(1, _)).pipe(doubleString).pipe(trimString)
    // "Hello1Hello"
    
    0 讨论(0)
  • 2021-01-06 11:13

    You can experiment with Scalaz:

      import scalaz._
      import Scalaz._
    
      def addNumber(i: Int, s: String) = s + i
      def doubleString(s: String) = (s + s, (s + s).length)
      def trimString(i: (String, Int)) = i._1.substring(0, i._2-1)
    
      def main(args: Array[String]) : Unit  =
        println(addNumber(2, "44") |> doubleString |> trimString)
    
    0 讨论(0)
提交回复
热议问题