Scala -- 3. Functions

Posted by GiaTuan on Tue, 18 Feb 2020 14:07:21 +0100

In Scala, methods and functions can be almost the same (for example, their definition, use and operation mechanism are the same), but the use of functions is more flexible and diverse. Functional programming is discussed from the perspective of programming mode (normal form). It can be understood as follows: functional programming regards function as first-class citizen, making full use of function, just multiple ways of using function. In Scala, function is first-class citizen, like variable, which can be used as parameter of function or assigned to a variable. The creation of function does not depend on it In Java, function creation depends on class, abstract class or interface. In Scala, functional programming and object-oriented programming are integrated.

1. Functional programming

Functional programming is a programming paradigm.
Functional programming is a kind of "structured programming", the main idea is to write the operation process as a series of nested function calls as much as possible.
In functional programming, functions are also treated as data types, because functions can also be accepted as inputs (parameters) and outputs (return values).
In functional programming, the most important is function.

2. Function form

def function name ([parameter name: parameter type] )[[: return value type] =]{

Statement...

Return return value

}

# =Indicates that the return value type is uncertain and needs type derivation
  def getRes(n1: Int, n2: Int, oper: Char) = {
    if (oper == '+') {
      n1 + n2 //Return
    } else if (oper == '-') {
      n1 - n2
    } else {
      //Return to null
      null
    }
  }

A, You can infer the function return value type according to the last line of code in the function body
def getSum(n1: Int, n2: Int): Int = {
n1 + n2
}
**The last expression is the function return value**
If the function has no parameters, it can be called without ()

B. If the return keyword is explicitly used by a function, the function return cannot be inferred by itself. In this case, it should be explicitly written as: return value type =, of course, if nothing is written, even if there is a return value ()

package hello

/**
 * @author Administrator 
 * @date 2020/2/16 9:29
 */
object Test1 {

  def main(args: Array[String]): Unit = {
    # Output ()
    print(fun1(1, 2))
    # output3
    print(fun2(1, 2))
  }

  def fun1(i: Int, j: Int) {
    return i + j
  }

  def fun2(i: Int, j: Int): Int = {
    return i + j
  }
}

C. Function nesting

object boke_demo01 {
 
  def main(args: Array[String]): Unit = {
 
    def f1(): Unit = { //ok private final
      println("f1")
    }
 
    println("ok~~")
 
    def sayOk(): Unit = { // private final sayOk$1 ()
      println("main sayOk")
 
      def sayOk(): Unit = { //  private final sayOk$2 ()
        println("sayok sayok")
      }
    }
 
  }
 
  def sayOk(): Unit = { //member
    println("main sayOk")
  }
}

D. Function parameter defaults

object boke_demo01 {
 
  def main(args: Array[String]): Unit = {
    println(sayOk("mary"))
  }
 
  //name the default value of parameter jack
  def sayOk(name: String = "jack"): String = {
    return name 
  }
}

E. Function named parameter

object boke_demo01 {
 
  def main(args: Array[String]): Unit = {
    //    mysqlCon()
    //    mysqlCon("127.0.0.1", 7777) / / overwrite from left to right
 
    //If we want to specify overriding a default value, we can use the named parameter, such as changing the user name and password
    mysqlCon(user = "tom", pwd = "123")
 
    //"V2" / (error)
    f6(p2 = "v2") // (?)
 
  }
 
  def mysqlCon(add: String = "localhost", port: Int = 3306,
               user: String = "root", pwd: String = "root"): Unit = {
    println("add=" + add)
    println("port=" + port)
    println("user=" + user)
    println("pwd=" + pwd)
  }
 
  def f6(p1: String = "v1", p2: String) {
    println(p1 + p2);
  }
 
}

F. The result type cannot be inferred before the recursive function is executed. There must be a clear return value type when using

 def f8(n: Int) = { //? error, recursion cannot use type inference, the returned data type must be specified
    if (n < 0)
      1
    else
      n * f8(n - 1)
 
}

G: Function variable parameter

//Supports 0 to more than one parameter
def sum(args : Int*) : Int = {
}
//Support 1 to more than one parameter
def sum(n1 : Int, args : Int*) : Int = {
}

3. procedure

def f10(name: String): Unit = {
println(name + "hello")
}
If the function declaration does not return a value type, but has an equal sign (=), you can infer the last line of code by type. At this time, the function actually has a return value, which is not a procedure.

4. Inertia function

When the return value of a function is declared as lazy, the execution of the function will be delayed until this value is taken for the first time. This function is called lazy function.

object boke_demo01 {
 
  def main(args: Array[String]): Unit = {
    lazy val res = sum(10, 20)
    println("-----------------")
    println("res=" + res) //Execute before using res
  }
 
  //sum function, return and
  def sum(n1: Int, n2: Int): Int = {
    println("sum() Implemented..") //Output a sentence
    return n1 + n2
  }
 
}

Lazy can't modify variables of var type. Not only when a function is called, but also when lazy is added, the execution of the function will be delayed. When a variable is declared, if lazy is declared, the allocation of variable values will also be delayed.

--Blueicex 2020/2/15 18:06 blueice1980@126.com

58 original articles published, praised 0, visited 2091
Private letter follow

Topics: Programming Scala Java