How to use an anonymous function in Scala

3 Answers

0 votes
// Anonymous function = A function with no identifier.

object Main {
  def main(args: Array[String]): Unit = {

    // Anonymous function (function literal) that takes two Ints and returns their sum.
    // (a, b) => a + b   ← this is Scala’s concise lambda syntax.
    val add: (Int, Int) => Int = (a, b) => a + b

    // Use the anonymous function
    val result = add(10, 20)

    println(result)
  }
}


/*
run:

30

*/

 



answered 1 day ago by avibootz
0 votes
object Main {
  def main(args: Array[String]): Unit = {

    val add = (a: Int, b: Int) => a + b

    println(add(10, 20))
  }
}


/*
run:

30

*/

 



answered 1 day ago by avibootz
0 votes
object Main {
  def main(args: Array[String]): Unit = {

    println(((a: Int, b: Int) => a + b)(10, 20))
  }
}


/*
run:

30

*/

 



answered 1 day ago by avibootz
...