Showing posts with label Scala Collection. Show all posts
Showing posts with label Scala Collection. Show all posts

Thursday, 5 May 2022

Scala Function - Collect

Scala Collection Collect

Collect apply given partial function on each element of input collection and it discard elements for which partial function is not defined.


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

  def collectExample(): Unit = {
    val divide: PartialFunction[Int, Int] = {
      case input: Int if(input != 0) => 100/input
    }
    val inputList = List(0, 0, 5, 15, 20)
    val res = inputList.collect(divide) // List(20, 6, 5) 100/5, 100/15, 100/20
    println(res)
  }
}






Scala Function - Chain

 Scala Collection - Chain:

Scala chain execute multiple function in sequence while taking same input type data as input.


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

  def chainExample() : Unit = {
    def appendCharAB = (input: String) => input + "AB"
    def appendCharXY = (input: String) => input + "XY"
    val res = Function.chain(List(appendCharAB, appendCharXY))("Prashant")
    println(s"Res = ${res}" ) //PrashantABXY

    def appendCharAB1 = (input: Int) => input + "AB1"
    def appendCharXY1 = (input: String) => input + "XY1"
    /*
      Below is not allowed as function appendCharAB1 should accept string not int
      val res1 = Function.chain(List(appendCharAB1, appendCharXY1))("Prashant")
      This is okay in andThen
    */
  }

}





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
  }

}