Anonymous Function: LAMBDA
Dream: Use the function as a first-class element like val and var, which can be passed to the function as parameters and returned from the function.
Problem: Scala is based on a JAVA VIRTUAL MACHINE, everything is an instance of the class.
let's understand how Scala solved this problem and made a function a first-class element.
By using the same concept of apply() function Scala provides predefined traits like MyFunction from Function1 to Function22.
Still, we are implementing the Function type and overriding apply() method. But Scala provides a nicer way to write all the codes called Lambda Function.
What is Lambda?
it is a Syntax sugar or shorthand for creating an instance of Functional trait and overriding apply() method.
By using LAMBDA a niceDoubler can be written as:
Following are some rules, to follow with LAMBDA function:
Rule 1: parameter type is optional, it is not required where it can be inferred
Rule 2: For a single parameter () is optional, but for multiple parameters () is mandatory.
Rule 3: No parameter function
Rule 4: _ can be used to represent parameters.
Note: To use _ type of function must be defined.