Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Functional programming

  • Object-oriented programming: solve problems, decompose objects, behaviors, attributes, and then solve problems through the relationship between objects and the invocation of behaviors
  • Functional programming: To solve a problem, break it down into steps, encapsulate each step (function), and solve the problem by calling these encapsulated steps.
  • The difference between functions and methods:
    • Function: A collection of program statements, called functions, that accomplish a function
      • Functions have no concept of overloading and overwriting
    • Methods: Functions in a class are called methods
      • Methods can be overridden and overridden

  • Functions in a class are called methods so they can be overridden and overridden, but functions in a method can’t, because functions can’t be overridden and overridden
Def main(): Unit = {} def main(args: Array[String]): Import java.util.Date new Date() // (2) def test(): java.util. Unit = {println(" no argument, no return value ")} test() def test(name: String): Unit = {println()} Unit = {def test3(name: String): Unit = {println(" function can be nested ")}}}}Copy the code

Basis function

Basic function syntax

  1. The basic grammar

The function definitions

  • Function 1: no parameters, no return value
Def test1(): Unit ={println(" no arguments, no returns ")} test1()Copy the code
  • Function 2: takes no parameters and has a return value
Def test2():String={return "no arguments, return value"} println(test2())Copy the code
  • Function 3: takes parameters and returns no value
Def test3(s:String):Unit={println(s)} test3("jinlian")Copy the code
  • Function 4: takes parameters and returns values
Def test4(s:String):String={return s+" return value "} println(test4("hello "))Copy the code
  • Function 5: multi-parameter, no return value
Def test5(name:String, age:Int):Unit={println(s"$name, $age")} test5("dalang",40)Copy the code
  • Function 6: multi-parameter, return value
Def test6(a:Int, b:Int):Int={println("6. Return a + b} test6(12,40)Copy the code

Function parameters

  • Variable parameter

  • If there are more than one parameter in the argument list, the variable parameter is usually placed last, because if the variable parameter is placed first, it is difficult to detect the second parameter

  • Parameter default value. Generally, parameters with default values are placed at the end of the parameter list

  • With name parameter

Function minimization principle

  • The return can be omitted; Scala uses the last line of the function body as the return value
  • If the function body has only one line of code, you can omit the curly braces
  • Return value type can be omitted if it can be inferred (: omitted with return value type)
  • If there is a return, the return value type cannot be omitted and must be specified
  • Even the return keyword in the function body does not work if the function explicitly declares unit
  • Scala can omit the equal sign if it expects a no-return type
  • If the function has no arguments but declares a list of arguments, the parentheses can be added with or without the function being called
  • If the function has no argument list, the parentheses can be omitted and must be omitted when called
  • If you do not care about the name but only the logical processing, the function name (def) can be omitted

Function senior

Higher-order functions

  1. Functions can be passed as values and
    val test = (name:String) => {println(name)}
    test("wrq")
Copy the code
  1. Functions can be passed as arguments
val test = (name:String) => {println(name)} test("wrq") println("---------------------------------") def test2(a:String => Unit):Unit={a(" ZJF ")} test2(test) equivalent toCopy the code

  1. Functions can be returned as function return values
def main(args: Array[String]): Unit = {def f1() = {def f2() = {} f2 _} val f = f1() So the variable f can continue to be called as a function f() // The above code can be simplified to f1()()}Copy the code

Anonymous functions

  • (x:Int)=>{function body} (x: indicates input parameter type; Int: indicates the input parameter type. Function body: represents concrete code logic.
// Define a binary operation function, Def dualFunctionOneAndTwo(fun (Int,Int) => Int, a:Int, b:Int):Int={ fun(a,b) } val add = (a:Int,b:Int) => a+b val minus = (a:Int, B :Int) => a-b println(dualFunctionOneAndTwo(add,1,2)) println(dualFunctionOneAndTwo(minus,3,4))Copy the code
  • The principle of minimalism for anonymous functions
    • The type of the parameter can be omitted and is automatically inferred from the parameter
    • If the type is omitted and only one argument is found, the parentheses can be omitted. Other cases: never omit parentheses with no arguments and arguments greater than 1.
    • If an anonymous function has only one line, the braces can also be omitted
    • If the argument appears only once, the argument is omitted and the following argument can be replaced by _
Test2 (test) test2((name:String) => {println(name)}) Test2 ((name) => {println(name)}) // (2); Other cases: never omit parentheses with no arguments and arguments greater than 1. Test2 (name => {println(name)}) // Test2 (println(_))Copy the code
  • Anonymous function exercises:
// Exercise 1: // Define an anonymous function and assign it as a value to fun. This function takes three arguments of type Int, String, Char, and Boolean. Fun (0, "", '0') returns false, otherwise returns true. val fun = (a:Int,b:String,c:Char) => { if (a == 0 && b.equals("") && c == '0') false else true } println(fun(0,"",'0')) // Exercise 2: function as return value // Define a function func that takes an Int and returns a function (called f1). // It returns the function f1, which takes a String argument and also returns a function (called f2). F2 takes // a Char argument and returns a Boolean value. // Call func(0) (" ") (' 0 ') to return false, otherwise return true. def func(i:Int):String => (Char => Boolean) = { def f1(s:String):(Char => Boolean) = { def f2(c:Char):Boolean = { if (i Def func(I: Int): = 0 &&s == "" &&c == '0') false else true} f2} f1} String => (Char => Boolean) = {s => c => if (I == 0 &&s == "" &&c == '0') false else true} // def func(I: Int)(s:String)(c:Char):Boolean = { if (i == 0 && s == "" && c == '0') false else true } println(func(0)("")('0'))Copy the code

Function Currization and closure

  1. Closure: If a function accesses the values of its external variables, the function and its environment are called closures
  2. Function currification: Transforms a list of arguments into a list of arguments.
  3. Code demo:
object TestFunction { def main(args: Array[String]): Unit ={def f1()={var a:Int = 10 def f2(b:Int)={a + b} f2 _} Println (f(3)) println(f1()(3)) // The function is currized, Def f3()(b:Int)={a + b} println(f3()(3))}}Copy the code

recursive

  • A function/method that calls itself inside a function/method is called a recursive call
// n! Def fact(n:Int):Int = {if(n == 0) return 1 fact(n-1) * n} println(fact(4))Copy the code

Control the abstract

  1. Value call: Passes the calculated value
  2. Name call: Pass the code
Def f(a:Int):Unit = {println(a)} Def myWhile(condition: =>Boolean): if (condition: =>Boolean): if (condition: =>Boolean): if (condition: =>Boolean): if (condition: =>Boolean): if (condition: =>Boolean): if (condition: =>Boolean): (=>Unit) =>Unit = {// def doLoop(op: =>Unit):Unit ={ if(condition){ op myWhile(condition)(op) } } doLoop _ } var n = 10 myWhile(n >= 1)({ println(n) n -= 1 })Copy the code

Lazy loading

  • When a function returns a value that is declared lazy, execution of the function is delayed until it is first evaluated
Def main(args: Array[String]): Unit = { lazy val res = sum(10, 30) println("----------------") println("res=" + res) } def sum(n1: Int, n2: Int): Int = {println("sum executed..." ) return n1 + n2 }Copy the code