Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining function in Scala using dot notation

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 I have 3 functions to apply to a value ( f1(f2(f3(value))) ), I have to do something like that:

(f1 _ andThen f2 andThen f3)(value)

Problems get even worse when the chain is longer and the functions require more than 1 parameter. F# solves this conundrum very elegantly with the '|>' operator, but that approach doesn't work well in Scala, since the language relies a lot on dot notation and currying is optional.

So the question is, is it possible to do something like this in Scala:

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)

addNumber(1,"Hello").doubleString.trimString

In other words can we chain functions using dot-notation, provided that they have different return types/arguments.

like image 791
Vateaux Avatar asked Feb 21 '19 20:02

Vateaux


1 Answers

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"
like image 74
Xavier Guihot Avatar answered Sep 28 '22 19:09

Xavier Guihot