Basic and advanced scala

Keywords: Scala Back-end

Methods and functions
Description of the distinction between the two
Scala has methods and functions. There is little semantic difference between them. In most cases, they are regarded as equivalent.
Scala method is a part of a class, and function is an object that can be assigned to a variable, that is, the function defined in the class is a method.
Methods in Scala are similar to those in Java. Methods are part of the constituent classes.
The function in Scala is a complete object. The function in Scala is actually an object that inherits the class of Trait.
In Scala, val statement can be used to define functions and def statement can be used to define methods.

Method definition
Define format

def functionName ([parameter list]) : [return type] = {
    function body
    return [expr]
}


Relevant description
If the equals sign and method body are not written, the method will be implicitly declared as an "abstract method", and the type containing it is also an abstract type.
return type can be any legal Scala data type. If the function has no return value, it can be returned as Unit, which is similar to Java void
Parameters in the parameter list can be separated by commas.

Method call
Call description
When you do not need to instantiate an object, you can use functionname (parameter list)
When you need to instantiate an object, it can be instance.functionname (parameter list)

closure
Closure concept
A closure is a function.
The process of function evaluation depends on one or more variables declared outside the function.
 

object TestCloseFunction {
    var factor = 1000
    def salaryMoney(i: Int): Int = {
    return i * factor
    }
    def main(args: Array[String]) {
        println("a monthly salary salaryMoney(8) value = " + salaryMoney(8))
        println("a monthly salary salaryMoney(10) value = " + salaryMoney(10))
        TestCloseFunction.factor = 10000;
        println("Annual salary salaryMoney(8) value = " + salaryMoney(8))
        println("Annual salary salaryMoney(10) value = " + salaryMoney(10))
    }
}


character string
Concept introduction
In Scala, the type of String is actually Java String, which has no String class.
Fully equivalent to java.lang.String

Immutable string creation

object TestString {
    var message = "happy new year!";
    var messageV2: String = "happy new year!";
    def main(args: Array[String]): Unit = {
        println(message);
        println(messageV2);
    }
}
Variable string creation(StringBuilder)
object TestStringBuilder {
    def main(args: Array[String]) {
        val stringBuilder = new StringBuilder;
        stringBuilder += '1'
        stringBuilder ++= "234"
        stringBuilder.append("567")
        stringBuilder.append('8')
        println("stringBuilder is : " + stringBuilder.toString);
    }
}


Method for finding string length
 

def main(args: Array[String]) {
    var str="12345678";
    println("str length()="+str.length());
}
String connection concat or+Symbol
def main(args: Array[String]) {
    var str = "12345678";
    var str2 = "9";
    println("str.concat(str2)=" + str.concat(str2));
    println("str.concat(str2)=" + str + str2);
}
String formatting printf
def main(args: Array[String]) {
    var name = "Dawn Education";
    var location = "Shijiazhuang";
    var work = "Big data skills training";
    var age=21;
    printf("I am%s,I am here%s,I do%s,I this year%d Years old",name,location,work,age);
}


array
Concept description
Used to store fixed size elements of the same type
Elements are accessed by index. The index of the first element is 0, and the index of the last element is the total number of elements minus 1

array define
Static array
 

def main(args: Array[String]): Unit = {
    var programLanguageArray = Array("java", "python", "c++", "c", "php")
    for (program <- programLanguageArray) {
        println(program);
    }
}


Dynamic array
 

def main(args: Array[String]): Unit = {
    var programLanguageArray = new Array[String](5)
    // var programLanguageArray:Array[String] = new Array[String](5)
    programLanguageArray(0) = "java";
    programLanguageArray(1) = "python";
    programLanguageArray(2) = "c++";
    programLanguageArray(3) = "c";
    programLanguageArray(4) = "php";
    for (program <- programLanguageArray) {
        println(program);
    }
}


Array traversal operation
 

def main(args: Array[String]): Unit = {
    var programLanguageArray = new Array[String](5)
    programLanguageArray(0) = "java";
    programLanguageArray(1) = "python";
    programLanguageArray(2) = "c++";
    programLanguageArray(3) = "c";
    programLanguageArray(4) = "php";
    println("strengthen for Loop traversal");
    for (program <- programLanguageArray) {
        println(program);
    }
    println("Array subscript loop traversal");
    for (i <- 0 to (programLanguageArray.length - 1)) {
        println(programLanguageArray(i))
    }
}


Multidimensional array
concept
Multidimensional array (> = 2) is an array of arrays, which is the same as the concept in Java
The elements in the array can be either the value of an entity or an array, and can be nested

Definition and application of most arrays
 

import Array.ofDim;
    object TestMultiArray{
    def main(args: Array[String]): Unit = {
        var myMatrix = ofDim[Int](4, 4)
        // Create a 2D matrix  
        for (i <- 0 to myMatrix.length - 1) {
            for (j <- 0 to myMatrix.length - 1) {
                myMatrix(i)(j) = (i + 1) * (j + 1);
            }
        }
        // Output two-dimensional square matrix
        for (i <- 0 to myMatrix.length - 1) {
            for (j <- 0 to myMatrix.length - 1) {
                print(" " + myMatrix(i)(j));
            }
            println();
        }
    }
}


Array merge
 

import Array.concat;
    object TestArray {
        def main(args: Array[String]): Unit = {
            var numberList1 = Array(1, 2, 3, 4)
            var numberList2 = Array(5, 6, 7, 8)
            var mergeList = concat(numberList1, numberList2)
            // Output all array elements
            for (x <- mergeList) {
                println(x)
            }
        }
    }


Create interval array
Interval array description

range() method to generate an array within an interval
The last parameter of the range() method is the step size, which is 1 by default
It is a half package interval, including the start value and excluding the end value, that is, start < = x < end

import Array.range;
    object TestArrayRange {
        def main(args: Array[String]): Unit = {
            var numberList1 = range(1, 5, 2)
            var numberList2 = range(1, 5)
            println("Manually set the step size to 2")
            // Output all array elements - numberList1
            for (x <- numberList1) {
                println(x)
            }
            println("The default step value is 1")
            // Output all array elements - numberList2
            for (x <- numberList2) {
                println(x)
            }
        }
    }


Function named call
Concept description
Call by value: first calculate the value of the parameter expression, and then apply it to the function. Just remove = > in the original way
Call by name: directly apply the non evaluated parameter expression to the function, and set the call by name with = >
Value transmission

object TestCallByValue {
    def main(args: Array[String]) {
        delayedCalculator(transmitMe());
    }
    def transmitMe(): String = {
        println("I am here transmitMe Method!")
        return "transmitMe Return value";
    } 
    def delayedCalculator(t: String): Unit = {
        println("stay delayedCalculator method--start")
        println("Formally call the passed function: " + t)
        println("stay delayedCalculator method--end")
    }
}


Name transmission

object TestCallByName {
    def main(args: Array[String]) {
        delayedCalculator(transmitMe());
    }
    def transmitMe(): String = {
        println("I am here transmitMe Method!")
        return "transmitMe Return value";
    }
    def delayedCalculator(t: => String): Unit = {
        println("stay delayedCalculator method--start")
        println("Formally call the passed function: " + t)
        println("stay delayedCalculator method--end")
    }
}


Call with specified function parameter name
 

object TestCallByParaName {
    def main(args: Array[String]) {
        printBabyNames(second = "Zhang Er", first = "Zhang Yi");
    }
    def printBabyNames(first: String, second: String): Unit= {
        println("The first child is called=" + first);
        println("The second child is called=" + second);
    }
}


Functions with variable (indefinite) parameters
 

object TestNonFixParas {
    def main(args: Array[String]) {
        printAllParasValue("one", "two", "three", "four");
    }
    def printAllParasValue(paras: String*): Unit = {
        for (temp <- paras) {
            println(temp);
        }
    } 
}


Default parameter value function
 

object TestDefaultParaFunction {
    def main(args: Array[String]) {
        println("Use the return value of the default value completely : " + salaryMoney());
        println("Part uses the return value of the default value : " + salaryMoney(10));
        println("Part uses the return value of the default value : " + salaryMoney(10,10000));
    }
    def salaryMoney(a: Int = 5, unit: Int = 1000): Int = {
        return a * unit
    }
}


Recursive function
 

object TestRecusive {
    def main(args: Array[String]) {
        var n=4
        println(n+"The factorial of is="+myFactorial(n))
    }
    def myFactorial(n: Int): Int = {
        if (n <= 1)
            return 1
        else
            return n * myFactorial(n - 1)
    }
}


Higher order function
Concept description
The first is to treat a function as a parameter of another function, that is, a function whose parameter is a function
The second type: the return value is the function of the function, that is, the higher-order function can produce a function with function parameters
Function with parameter function

object TestHighFunctionByTransmitFunctionPara {
    def main(args: Array[String]) {
        delayedCalculator(transmitMe());
    }
    def transmitMe(): String = {
        println("I am here transmitMe Method!")
        return "transmitMe Return value";
    } 
    def delayedCalculator(t: => String): Unit = {
        println("stay delayedCalculator method--start")
        println("Formally call the passed function: " + t)
        println("stay delayedCalculator method--end")
    }
}


The return value is the function of the function

object TestHighFunctionByRetFunction {
    def main(args: Array[String]) {
        var mySalaryFun=multiplyBy(1000);
        println(mySalaryFun(10));
    }
    def multiplyBy(salaryUnit:Int)=(x:Int)=>salaryUnit*x
}


Nested Function
Concept introduction
A function is defined within a function. The functions defined within a function are called local functions, also known as embedded functions
 

object TestEmbedFunction {
    def main(args: Array[String]) {
        var msg="HelloWorld";
        printMessage(msg);
    }
    def printMessage(msg: String): Unit = {
        def printMessageInner(msg: String): Unit = {
            println(msg);
        }
        printMessageInner(msg);
    }
}


Anonymous function
Concept introduction
Function without function name
To make the code more concise, it is represented by = >. The parameter list is on the left and the function body is on the right

Anonymous usage (function implementation that increases the value by + 1)
 

//Function definition:
var inc = (x:Int) => x+1
//Function usage:
var x = inc(8)+1
 Normal writing (self increment of value)+1 Function implementation of)
//Normal definition:
def incFunction(x: Int): Int = {
    return x + 1;
}
//Function usage:
var x=incFunction(8)+1


Partial application function
Concept description
You do not need to provide all the parameters required by the function, only some or no required parameters
Implementation method: bind some parameters of the function, and replace the unbound part with "" to form a partial application function

Traditional method (say hello to sb)

import java.util.Date
    object TestPartialParasFunction {
        def main(args: Array[String]) {
            val name="Zhang San"
            sayHello(name, "Good morning")
            Thread.sleep(1000)
            sayHello(name, "Good noon")
            Thread.sleep(1000)
            sayHello(name, "Good evening")
        }
        def sayHello(name: String, message: String)= {
            println(name + "----" + message)
        }
    }


Partial application function implementation (say hello to someone)

def main(args: Array[String]) {
    val name="Zhang San"
    val partialSay=sayHello(name,_:String);
    partialSay("Good morning")
    Thread.sleep(1000)
    partialSay("Good noon")
    Thread.sleep(1000)
    partialSay("Good evening")
}
def sayHello(name: String, message: String) = {
    println(name + "----" + message)
}


Function coritization
Concept description
The process of changing the original function that accepts two parameters into a new function that accepts one parameter. The new function returns a function with the original second parameter as the parameter.
It improves the flexibility of the use method

Traditional add method definition

def add(x: Int, y: Int) = x + y;


The traditional add method uses

def main(args: Array[String]) {
    println(add(3,4));
}
def add(x: Int, y: Int) = x + y;


add method definition of Coriolis implementation

def add(x:Int)(y:Int) = x + y


Implementation of add method using Coriolis

object TestCurryingFunction {
    def main(args: Array[String]) {
        //Use of corrilized form 1
        var curryingAdd1 = add1(3)
        //Use of corrilized form 2
        var curryingAdd2 = add2(3)(_)
        println(curryingAdd1(4));
        println(curryingAdd1(4));
    }
    //Curry form 1
    def add1(x: Int) = (y: Int) => x + y;
    //Curry form 2
    def add2(x: Int)(y: Int) = x + y;
}


aggregate
list
   

 //List
    val list1:List[String] = List("tom","jack")
    list1.foreach(x=>println(x))


Use Nil and:: to build lists

   

    //Building linked lists using Nil
    val list2 = "antg"::("jack"::("tom"::Nil))
    list2.foreach(x=>println(x))


 

Posted by Gecko24 on Fri, 12 Nov 2021 08:43:45 -0800