Monday 16 May 2022

Scala Function - Corresponds

The corresponds checks two collection indexes by index using the given predicate. 

Here isEven is a predicate that checks whether input numbers are even or not.

If this predicate returns for all the elements then corresponds will return true else false.

  def correspondsExample(): Unit = {
    def isEven = (input: Int, otherInput: Int) => (input % 2 == 0 && otherInput %2 ==0)
    val numberList = List(2,4,6,7)
    val numberList1 = List(22,24,26,28)
    val output: Boolean = numberList.corresponds(numberList1)(isEven)
    println(s"Comparing two list using corresponds - example1 : ${output}") //false

    val numberList2 = List(2,4,6)
    val numberList3 = List(32,44,88)
    val output1: Boolean = numberList2.corresponds(numberList3)(isEven)
    println(s"Comparing two list using corresponds - example1 : ${output1}") // true
  }


No comments:

Post a Comment