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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With