Saturday 7 May 2022

Scala Function Const

Function.Const create an anonymous function which return same output for any input or some fixed input.

In below example it gives output 12 for any input. 


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

  def constExample(): Unit = {
    val res: Any => Int = Function.const(12)
    val result = res("passAnything")
    println(s"Result by passing anything : ${result}" ) // result will be constant for any input as 12.
   
    //This can be useful to pass to higher order function
    val someList = List("anything", 8, 1298)
    val listWithSameElement = someList.map(Function.const(12))
    println(s"Function.Const pass as higher order function ${listWithSameElement}") //List(12, 12, 12)
  }

}


No comments:

Post a Comment