In Scala, An anonymous function is called a function literal. A function which doesn’t contain a name is called an anonymous function. An anonymous function gives a simple function definition. It is used when we need to make an inline function.
use case 1: Anonymous Function without parameters
// Scala program to illustrate the anonymous method
object prwatech{
def main(args: Array[String])
// Creating anonymous functions without parameter
var myfun1 = () => {"Welcome to Prwatech !"}
println(myfun1())
// A function which contain anonymous function as a parameter
def myfunction(fun:(String, String)=> String) =
{
fun("BigData", " hadoop")
}
// Explicit type declaration of anonymous function in another
function
val f1 = myfunction((str1: String,
str2: String) => str1 + str2)
// Shorthand declaration using wildcard
val f2 = myfunction(_ + _)
println(f1)
println(f2)
}
}
output:
Welcome to Prwatech !
BigData hadoop
BigData hadoop
use case 2: Anonymous function with parameter
// Scala program to illustrate the anonymous method
object prwatech
{
def main(args: Array[String])
// Creating anonymous functions with multiple parameters
Assign
// anonymous functions to variables
var myfunction1 = (str1:String, str2:String) => str1 + str2
// An anonymous function is created
var myfunction2 = (_:String) + (_:String)
// Here, the variable invoke like a function call
println(myfunction1("Big Data", " Prwatech"))
println(myfunction2("Data Science", " Prwatech"))
}
}
output
Big Data Prwatech
Data Science Prwatech
use case 3:
// Scala program to illustrate the anonymous method
object prwatech
{
def main(args: Array[String])
// Creating anonymous functions
// with multiple parameters Assign
var myfunction1 = (str1:String, str2:String) => str1 + str2
// An anonymous function is created
var myfunction2 = (_:String) + (_:String)
// one more anonymous function is created
var myfunction3 = (_:String) + (_:String)
// Here, the variable invoke like a function call
println(myfunction1("Big Data", " Prwatech"))
println(myfunction2("Data Science", " Prwatech"))
println(myfunction3("Tableau", " Prwatech"))
}
}
output
Big Data Prwatech
Data Science Prwatech
Tableau Prwatech