Scala Functional Programming

The function assigned to the variable

// Scala functions are first-class citizens, it can be defined independently, independent existence, but also directly as a function of the value assigned to the variable

// Scala syntax specified, when the function is assigned to a variable, you must add a space and an underscore after the function

 

def sayHello(name: String) { println("Hello, " + name) }

val sayHelloFunc = sayHello _

sayHelloFunc("leo")

 

 

 Anonymous function

// Scala , the function may not need to name, anonymous function at this time functions are called. // After the direct-defined function, the function will be assigned to a variable; anonymous function can also be defined directly passed among other functions

// Scala define an anonymous function syntax rules is that ( parameter name : parameter type ) => function body

// this syntax anonymous function must deeply understand and master, the spark of a large number of the syntax, if not mastered, can not read spark source

 

val sayHelloFunc = (name: String) => println("Hello, " + name)

 

 

Higher-order functions

// Scala , since functions are first-class citizens, and therefore can be passed directly to a function other functions as arguments. This function is extremely powerful, but also Java this object-oriented programming languages are not available.

// receiving function as a function of other parameters, also referred to as higher-order function ( IN AREAS OF COMMUNICAITIONS-Order function )

val sayHelloFunc = (name: String) => println("Hello, " + name)

def greeting(func: (String) => Unit, name: String) { func(name) }

greeting(sayHelloFunc, "leo")

 

Array (1, 2, 3, 4, 5) .Map ((num: Int) => num * num)

 

// higher-order functions Another function is to function as a return value

def getGreetingFunc(msg: String) = (name: String) => println(msg + ", " + name)

val greetingFunc = getGreetingFunc("hello")

greetingFunc("leo")

 

Higher-order functions of type inference

 

// higher order function can automatically infer parameter type, without the need to specify the type; but also for only one function parameter which can also be eliminated parentheses; if only one parameter is used only once in the right side of the body function , the received parameters may also be omitted, and the parameters _ instead

// such as 3 * _ this syntax, we must grasp! ! spark source code makes extensive use of this syntax!

 

def greeting(func: (String) => Unit, name: String) { func(name) }

greeting((name: String) => println("Hello, " + name), "leo")

greeting((name) => println("Hello, " + name), "leo")

greeting(name => println("Hello, " + name), "leo")

 

def triple(func: (Int) => Int) = { func(3) }

triple(3 * _)

 

Scala common higher-order functions

// map: for each element are mapped incoming returns after a processing element

Array(1, 2, 3, 4, 5).map(2 * _)

 

// foreach: for each element of the incoming are processed, but no return value

(1 to 9).map("*" * _).foreach(println _)

 

// filter: for each element are passed will be evaluated, if the return of the element to true , the element is retained, otherwise filter out the elements

(1 to 20).filter(_ % 2 == 0)

 

// reduceLeft: from the left element, a reduce operation, i.e. before the elements 1 and element 2 are processed, and then the result elements 3 processes the results to the element 4 treatment, and so on, that is reduce ; reduce operation you must master! spark programming focus! ! !

// The following operation is equivalent to 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9

(1 to 9).reduceLeft( _ * _)

 

// sortWith: the elements of the pairwise comparison, sorting

Array(3, 2, 5, 4, 10, 1).sortWith(_ < _)

 

Closure

// Closure of the most succinct explanation: when function arguments are not valid in its scope, but also can access the variables, namely closure

 

def getGreetingFunc(msg: String) = (name: String) => println(msg + ", " + name)

val greetingFuncHello = getGreetingFunc("hello")

val greetingFuncHi = getGreetingFunc("hi")

 

// two calls getGreetingFunc function, passing a different msg , and create a different function returns

// However, msg just a local variable, but in getGreetingFunc after performing, you can continue to exist in function created; greetingFuncHello ( "LEO") , when you call, the value of "hello" in the msg is retained in the body of the function inside, you can repeatedly use

// this variable is beyond its scope, the case can be used further, i.e. the closure

 

// Scala to achieve closure by creating an object for each function, in fact, for getGreetingFunc function functions created, msg as a variable function object exists, so each function can have different msg

 

// Scala compiler will ensure that these closure mechanism

 

SAM conversion

// in Java is not supported directly to the function passed as a parameter to a method, generally speaking, the only way is to define an instance of an object class implements an interface, the object is only one way; these interfaces are only single abstract method, i.e. sINGLE abstract method , simply referred to as SAM

 

// Because Scala can call Java code, so when we call Java when a method may have to create the SAM method to transfer, very troublesome; however Scala is supported by direct transfer function. At this point you can use Scala offered, calling Java when the method used functions, SAM conversion, the upcoming SAM converted Scala function

 

// To use SAM conversion, you need to use Scala features provided, implicit conversion

 

import javax.swing._

import java.awt.event._

 

val button = new JButton("Click")

button.addActionListener(new ActionListener {

  override def actionPerformed(event: ActionEvent) {

    println("Click Me!!!")

  }

})

 

implicit def getActionListener(actionProcessFunc: (ActionEvent) => Unit) = new ActionListener {

  override def actionPerformed(event: ActionEvent) {

    actionProcessFunc(event)

  }

}

button.addActionListener((event: ActionEvent) => println("Click Me!!!"))

 

 

Currying function

// Curring function, means that the two parameters a received original function, converted into two functions, the first function of the first parameter previously received, then the previously received back a second function of the second parameter .

// During the function call, it becomes the form of two successive function calls

// in Spark source code, there are also reflected, so () () This form of Curring function, must master!

 

def sum(a: Int, b: Int) = a + b

sum(1, 1)

 

def sum2(a: Int) = (b: Int) => a + b

sum2(1)(1)

 

def sum3(a: Int)(b: Int) = a + b

 

Return

 

// Scala , the need to use return to return a value, the value of the last line of the statement of function function is the return value of the function. In Scala in, return to the return value of the function name to the band containing the anonymous function, and as a return value of the function with the name anonymous function.

// use the return of the anonymous function, it must be given return type, or can not be compiled

 

def greeting(name: String) = {

  def sayHello(name: String):String = {

    return "Hello, " + name

  }

  sayHello(name)

}

 

 

Guess you like

Origin www.cnblogs.com/YuanWeiBlogger/p/11432585.html