Learn a little bit of Scala anonymous function every day
1. Definition
If a function has no name, it is an anonymous function. It is only used once, and it is not called many times
2. Usage scenarios of anonymous functions
Assign anonymous functions directly to variables
Use anonymous functions as arguments to the function
3. How many representations of anonymous functions? Or the form of presentation
An anonymous function with no parameter input and no return value
An anonymous function with parameter input and no return value
Anonymous function with parameter input and return value
4. There are two forms of syntax rules for anonymous functions: [one has input parameters, the other has no input parameters]
(parameter name: parameter type) = > function body
Function body
Package com.xej.learning.nimingFunctionobject AnonymousFunction {def main (args: Array [String]): Unit = {/ / for anonymous functions with parameter input, you should also use parameter input oh kafkaName ("apache kafka") println ("-->:\ t" + flumeName ("apache flume")) sparkName / / anonymous function usage scenario-- 1, as a parameter, pass it to the higher-order function / / below In map,foreach It is the anonymous function Array (3 Int 2). Map {(x: println) = > x + 2} .foreach (x = > print (x + ")) Array ("\ nMutual-") Map {_ + 1} .foreach (x = > print (x + "))} / / usage scenarios of anonymous functions-- 2 Directly assign value to variable / / parameter: parameter input, function body: no return value, anonymous function / / function body, there may be many statements in the form of anonymous function / / function body, oh, / only the final result, is val kafkaName = (name: String) = > println ("--kafka-- >" + name) / / Parameter: parameter input, function body: return value Anonymous function val flumeName = (name: String) = > "--flume-- >" + name / / Parameter: no parameter input, function body: no return value, anonymous function val sparkName = println ("- this is spark-")}
Anonymous functions are widely used in spark source code and marathon source code.
The following is an example of the marathon source code