Categories
scala

Anonymous function in scala

In this post let us learn about the anonymous function in scala.

Anonymous function in scala

Anonymous function is the function without any specific name. It is also called as Lambda function .

Lambda is the word derived from the word lambda calculus which is the  mathematical expression of functional programming.

Basic syntax

To have a little introduction about the functions in scala , go through the previous blog in scala.

The following is the basic syntax to define anonymous function with single parameter.

val a: Int => Int = (x : Int) => x * 2
println(a(3))
6

There are alternative ways for defining the same , the followings are those.

val b = (x : Int) => x * 2
println(b(3))
6

For further information on the syntax of anonymous function in scala

val c = (_:Int) * 2
println(c(3)
6

With multiple parameters

If you have multiple parameters , need to mention the arguments within parenthesis. The below will be the syntax for anonymous function with multiple parameters.

val d: (Int,Int) => Int = (x : Int, y: Int) => x * y
println(d(3,3))
9

With no parameter

In the following example println(e) prints the instance , whereas println(e()) prints the value of the function . We might used to call objects in the former way but for lambda , we must use the latter way.

val e: () => Int = () => 2
println(e())
2

Using Curly braces

The following is the anonymous function defined using curly braces.

val f = { (colour: String) => colour.toInt}

MOAR syntactic sugar

val g: Int => Int = (x: Int) => x+1 — This line is equivalent to the below

val g: Int => Int = _+1
println(g(3))
4

val h: (Int,Int) => Int = (a,b) => a+b — This is equivalent to the below

val h: (Int,Int) => Int = _+ _
println(h(3,3))
6