scala -- format and usage of function + lazy lazy usage + difference between method and function + method calling method

Keywords: Scala Database Big Data Data Warehouse

1. Method

1.1 general

In actual development, we need to write a large number of logic codes, which is bound to involve repeated requirements. For example, for the maximum values of 10 and 20 and the maximum values of 11 and 22, the logic code for comparison needs to be written twice. If the logic code for comparison is put into the method, it only needs to be written once, This is the method. Methods in scala are similar to Java methods, but the syntax of scala and Java definition methods is different.

1.2 syntax format

def Method name(Parameter name:Parameter type, Parameter name:Parameter type) : [return type] = {
    //Method body
}

be careful:

  • The parameter type of the parameter list cannot be omitted
  • The return value type can be omitted and automatically inferred by the scala compiler
  • The return value may not be written with return. By default, it is the value of the {} block expression

1.3 example

**Requirements:**

  1. Define a method getMax to get the maximum value of two integer numbers and return the result (maximum value)
  2. Call this method to get the maximum value and print the result to the console

Reference code

  • Mode 1: Standard Writing
//1. Define a method to obtain the maximum value of two integers
def getMax(a:Int, b:Int): Int = {
    return if(a > b) a else b
}
//2. Call the method to get the maximum value
val max = getMax(10, 20)
//3. Print results
println("max: " + max)
  • Mode 2: optimized version
//1. Define a method to obtain the maximum value of two integers
def getMax(a:Int, b:Int) = if(a > b) a else b
//2. Call the method to get the maximum value
val max = getMax(22, 11)
//3. Print results
println("max: " + max)

1.4 inference of return value type

Scala definition method can omit the data type of the return value, and scala automatically infers the return value type. This method is more concise after definition.

Note: when defining a recursive method, the return value type cannot be omitted

Example

Define a recursive method to find the factorial of 5

step

  1. Define the method factorial, which is used to calculate the factorial of a number

    Law: the factorial of 1 is equal to 1, and the factorial of other numbers is: n= n * (n - 1)!

  2. Call the method, get the factorial of 5, and print the result to the console

Reference code

//1. Define the factorial method to calculate the factorial of a number
def factorial(n:Int):Int = if(n == 1) 1 else n * factorial(n - 1)
//2. Call the method to obtain the factorial of 5
val result = factorial(5)
//3. Print the results to the console
println("result: " + result)

1.5 inert method

When the variable recording the return value of the method is declared lazy, the execution of the method will be delayed until we use the value for the first time. Methods like this are called lazy methods

be careful:

  1. Java It does not provide original ecological information"inertia"technology, However, it can be implemented through a specific code structure, This structure is called: Lazy loading(Also called delayed loading)
  2. lazy Cannot modify var Variable of type. 

Usage scenario:

  1. Open database connection

    Because expression execution is expensive, we want to delay the operation until we really need the expression result value

  2. Increase the startup time of some specific modules

    In order to shorten the start-up time of the module, some work that is not currently needed can be postponed

  3. Ensure that some fields in the object can be initialized first

    In order to ensure that some fields in the object can be initialized first, we need to inert other fields

demand

Define a method to get the sum of two integers, call the method through "lazy" technology, and then print the result

Reference code

//1. Define a method to obtain the sum of two integers
def getSum(a:Int, b:Int) = {
    println("getSum Method was executed...")
    a + b
}
//2. Call this method in a "lazy" manner
lazy val sum = getSum(1, 2)		//At this point, we found that the getSum method was not executed, indicating that its execution was delayed

//3. Print the results and observe
println("sum: " + sum) 			//The print result is sum: 3, indicating that the method will be loaded and executed only when the method return value is used for the first time

1.6 method parameters

The method parameters in scala are used flexibly. It supports the following types of parameters:

  • Default parameters
  • Named parameter
  • Variable length parameter
1.6.1 default parameters

When defining a method, you can define a default value for the parameter.

Example

  1. Define a method to calculate the sum of two integers. The default values are 10 and 20 respectively
  2. Call this method without passing any parameters

Reference code

//1. Define a method to obtain the sum of two integers
// x. The default values for y are 10 and 20, respectively
def getSum(x:Int = 10, y:Int = 20) = x + y
//2. Call the method in the form of default parameters
val sum = getSum()
//3. Print results
println("sum: " + sum)
1.6.2 named parameters

When calling a method, you can specify the name of the parameter to call.

Example

  1. Define a method to calculate the sum of two integers. The default values are 10 and 20 respectively
  2. Call this method to set only the value of the first parameter

Reference code

//1. Define a method to obtain the sum of two integers
def getSum(x:Int = 10, y:Int = 20) = x + y
//2. Call the method in the form of default parameters
val sum = getSum(x=1)
//3. Print results
println("sum: " + sum)
1.6.3 variable length parameters

If the parameters of a method are not fixed, the parameters of the method can be defined as variable length parameters.

Syntax format:

def Method name(Parameter name:Parameter type*):return type = {
    //Method body
}

be careful:

  1. Add a after the parameter type`*`Number, indicating that the parameters can be 0 or more
  2. A method has and can only have one variable length parameter, And the variable length parameter should be placed at the last edge of the parameter list.

**Example 1:**

  1. Define a method for calculating the addition of several values
  2. Call the method and pass in the following data: 1,2,3,4,5

Reference code

//1. Define a method for calculating the addition of several values
def getSum(a:Int*) = a.sum
//2. Call the method, pass in some integers, and get their sum
val sum = getSum(1,2,3,4,5)
//3. Print results
println("sum: " + sum)

1.7 method calling method

In scala, there are several methods to call:

  • Suffix tone usage
  • Infix tone usage
  • Curly bracket tone usage
  • Parenthesis free usage

Note: these methods are often used when writing spark and flink programs.

1.7.1 suffix adjustment usage

This method is no different from Java and is very simple

grammar

Object name.Method name(parameter)

Example

Use the suffix method to call Math.abs to find the absolute value

Reference code

//Suffix tone usage
Math.abs(-1)	//The result is 1
1.7.2 infix tone usage

grammar

Object name method name parameter

For example: 1 to 10

Note: if there are multiple parameters, use parentheses

Example

Use infix method to call Math.abs to find the absolute value

//Infix tone usage
Math abs -1		//The result is 1

Extension: operator is method

Look at an expression. Do you think it looks like a method call?

1 + 1

In scala, + - * /% and other operators are the same as Java, but in scala,

  • All operators are methods
  • An operator is a method whose name is a symbol
1.7.3 use of curly braces

grammar

Math.abs{ 
    // Expression 1
    // Expression 2
}

Note: curly braces can be used only if the method has one parameter

Example

Use curly braces to call Math.abs to find the absolute value

Reference code

//Curly bracket tone usage
Math.abs{-10}	//The result is: 10
1.7.4 usage without parentheses

If the method has no parameters, you can omit the parentheses after the method name

Example

  • Define a parameterless method and print "Hello, Scala!"
  • The method is called using the bracketed calling method

Reference code

//1. Define a method without parameters and print "Hello, Scala!"
def sayHello() = println("Hello, Scala!")
//2. Call method
sayHello

be careful:

  1. In Scala, if the return value type of a method is Unit, such a method is called a procedure
  2. The equal sign (=) of the process can be omitted without writing. For example:
def sayHello() = println("Hello, Scala!")   
//Can be rewritten as
def sayHello() { println("Hello, Scala!") }	 //Note: this curly bracket {} cannot be omitted

2. Function

scala supports functional programming. In the future, Spark/Flink programs will use a lot of functions. At present, we will make a simple introduction to functions. In the subsequent learning process, we will gradually focus on the usage of functions

2.1 defining functions

grammar

val Function variable name = (Parameter name:Parameter type, Parameter name:Parameter type....) => Function body

be careful:

  • In Scala, a function is an object (variable)
  • Similar to methods, functions also have parameter lists and return values
  • Function definitions do not require def definitions
  • There is no need to specify the return value type

2.2 example

**Requirements:**

  1. Defines a function that calculates the sum of two integers
  2. Call this function

Reference code

//1. Define a function to calculate the sum of two integers and assign it to the variable sum
val getSum = (x:Int, y:Int) => x + y
//2. Call function
val result = getSum(1,2)
//3. Print results
println("result: " + result)

2.3 differences between methods and functions

In Java, there is no difference between methods and functions, but their names are different. However, in Scala, functions and methods are different, as follows:

  • A method belongs to a class or object. At run time, it is loaded into the method area of the JVM
  • You can assign a function object to a variable that is loaded into the JVM's heap memory at run time
  • A function is an object that inherits from FunctionN. The function objects include apply, curred, toString and tupled methods. The method does not

Conclusion: in Scala, a function is an object and a method belongs to an object, so it can be understood as: a method belongs to a function

Example

The demo method cannot be assigned to a variable

//1. Definition method
def add(x:Int,y:Int)= x + y

//2. Try to assign a method to a variable
//val a = add(1, 2) 		// Don't write it like this. It's "calling a method", not assigning a method to a variable
val a = add

//3. The above code will report an error
<console>:12: error: missing argument list for method add
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `add _` or `add(_,_)` instead of `add`.
       val a = add

2.4 method conversion to function

Sometimes it is necessary to convert a method into a function. For example, if it is passed as a variable, it is necessary to convert a method into a function

format

val Variable name = Method name _		//The format is: method name + space + underscore

Note: use_ You can convert a method to a function

Example

  1. Define a method to calculate the sum of two integers
  2. The method is converted into a function and assigned to a variable

Reference code

//1. Define a method to calculate the sum of two integers
def add(x:Int, y:Int)= x + y
//2. Convert the method into a function and assign it to a variable
val a = add _
//3. Call the function to get the sum of two integers
val result = a(1, 2)
//4. Print results
println("result: " + result)

3. Case: print nn multiplication table

3.1 requirements

Define the method implementation, and print the corresponding multiplication table according to the integer entered by the user.

For example, if you enter 5, the 55 multiplication table will be printed, and if you enter 9, the 99 multiplication table will be printed.

3.2 purpose

  1. Investigate the keyboard input and methods, and the comprehensive application of functions
  2. Experience the difference between methods and functions

3.3 steps

  1. Define a method (or function) to receive an integer parameter
  2. Through for loop nesting, print the corresponding multiplication table according to the incoming integer
  3. Call the method (function) and output the result

3.4 reference code

  • Method 1: realized by method
//1. Define a method to receive an integer parameter
def printMT(n:Int) = {   //Multiplication table
    //2. Through the nesting of for loop, print the corresponding multiplication table according to the incoming integer
    for(i <- 1 to n; j <- 1 to i) {
    	print(s"${j} * ${i} = ${j * i}\t"); 
        if(j==i) println()
    }
}
//3. Call method
printMT(5)

//Optimized version: the code of the above definition method can be combined into one line (as long as it can be understood at present)
/*def printMT(n:Int) = for(i <- 1 to n; j <- 1 to i) print(s"${j} * ${i} = ${j * i}" + (if(j==i) "\r\n" else "\t"))*/
  • Mode 2: realized by function
//1. Define a function to receive an integer parameter
val printMT = (n:Int) => {
    //2. Through the nesting of for loop, print the corresponding multiplication table according to the incoming integer
    for(i <- 1 to n; j <- 1 to i) {
    	print(s"${j} * ${i} = ${j * i}\t"); 
        if(j==i) println()
    }
}
//3. Call function
printMT(9)

//Optimized version: the code of the above defined function can be combined into one line (as long as it can be understood at present)
/*val printMT = (n:Int) => for(i <- 1 to n; j <- 1 to i) print(s"${j} * ${i} = ${j * i}" + (if(j==i) "\r\n" else "\t"))*/

Posted by tony-kidsdirect on Thu, 25 Nov 2021 16:45:14 -0800