Thursday 5 May 2022

Scala Function - andThen

 Scala Collection andThen:


andThen creates an anonymous function that pass input to first function and it's output pass to second function

Both function can take different data types as input.

Note: Scala chain is similar to andThen only difference is that it can chain multiple functions and all function should have input with same data type.

object MyBlog {
  def main(args: Array[String]): Unit = {
    andThenExample()
  }

   def andThenExample() : Unit = {
    val add10 = (x:Int) => x + 10
    val add20 = (x:Int) => x + 20
    val addthen = add10 andThen(add20)
    val res = addthen(10)
    // 10 is passed to add10 and then it's output 20 pass to
    // next function add20.
    println(res) // 10 + 10 = add20(20) // 40
  }

}

No comments:

Post a Comment