In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.
Syntax:
(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)
- In the above first syntax, => is known as a transformer. The transformer is used to transform the parameter-list of the left-hand side of the symbol into a new result using the expression present on the right-hand side.
- In the above second syntax, _ character is known as a wildcard is a shorthand way to represent a parameter who appears only once in the anonymous function.
Anonymous Functions With Parameters
When a function literal is instantiated in an object is known as a function value. Or in other words, when an anonymous function is assigned to a variable then we can invoke that variable like a function call. We can define multiple arguments in the anonymous function.
Example 1:
object Main
{
def main(args : Array[String])
{
var myfc 1 = (str 1 : String, str 2 : String) => str 1 + str 2
var myfc 2 = ( _: String) + ( _: String)
println(myfc 1 ( "Geeks" , "12Geeks" ))
println(myfc 2 ( "Geeks" , "forGeeks" ))
}
}
|
Output:
Geeks12Geeks
GeeksforGeeks
Anonymous Functions Without Parameters
We are allowed to define an anonymous function without parameters. In Scala, We are allowed to pass an anonymous function as a parameter to another function.
Example 2:
object Main
{
def main(args : Array[String])
{
var myfun 1 = () => { "Welcome to GeeksforGeeks...!!" }
println(myfun 1 ())
def myfunction(fun : (String, String) => String) =
{
fun( "Dog" , "Cat" )
}
val f 1 = myfunction((str 1 : String,
str 2 : String) => str 1 + str 2 )
val f 2 = myfunction( _ + _ )
println(f 1 )
println(f 2 )
}
}
|
Output:
Welcome to GeeksforGeeks...!!
DogCat
DogCat