In functional programming, functions serve as lego blocks which you connect to build your system. One such wiring together of the blocks would be a serial connection — one function followed by another function.
Input goes to the first function and the output from the first function goes as the input to the second function. This technique is what the built in support of “andThen” in a scala function captures/provides.
Let us say, we had a function “twice” which doubles the input value. It would look as below.
val twice:Function1[Int,Int] = (a:Int)=> a* 2
Let us say we had another function “addTen” that adds ten to the input value.
val addTen[Int,Int] = (a:Int) => a+ 10
Now, if you want to double a value and then add ten, you can use “andThen” to achieve this.
val doubleAndAddTen:Function[Int,Int] = twice.andThen(addTen)
Now, if you call doubleAndAddTen function on a value (say 5), 5 would go in as input to the “twice” function which would return 10 which would then go as input to the “addTen” function to result in the value 20.
println(doubleAndAddTen(5)