Does anyone have an example of how to use andThen with lists? I noticed that andThen is defined for List, but there is no example in the docs to show how to use it.
I understand that f and Ten g means executing function f and then executing function g. The input of the function g is derived from the function f. It's right?
Question 1 - I wrote the following code, but I do not understand why I should use andThen, because I can achieve the same result with the map.
scala> val l = List(1,2,3,4,5) l: List[Int] = List(1, 2, 3, 4, 5) //simple function that increments value of element of list scala> def f(l:List[Int]):List[Int] = {l.map(x=>x-1)} f: (l: List[Int])List[Int] //function which decrements value of elements of list scala> def g(l:List[Int]):List[Int] = {l.map(x=>x+1)} g: (l: List[Int])List[Int] scala> val p = f _ andThen g _ p: List[Int] => List[Int] = <function1> //printing original list scala> l res75: List[Int] = List(1, 2, 3, 4, 5) //p works as expected. scala> p(l) res74: List[Int] = List(1, 2, 3, 4, 5) //but I can achieve the same with two maps. What is the point of andThen? scala> l.map(x=>x+1).map(x=>x-1) res76: List[Int] = List(1, 2, 3, 4, 5)
Can anyone share practical examples where andThen is more useful than methods like filter, map, etc. One example that I could see above is that with andThen I could create a new function p, which is a combination of other functions. But this use reveals the usefulness of andThen, not List and andThen
source share