Basic Summary of Scala

Keywords: Java Scala

1. Basic concepts

  • Basic concepts
    • Class: The abstraction of objects of the same type, such as people, planets, cars, etc.
    • Object: A specific instance of a class containing properties and methods such as a person, a planet, a vehicle, and so on
    • Attributes: Used to describe certain characteristics of an object, such as a person's age, name, etc.
    • Method: Used to describe certain functions of the object, such as people eating, learning, etc.
    • The file ends with.scala
    • Main program entry: def main(args: Array[String]): Unit {}
  • identifier
    • Compatible with java identifier naming conventions
    • Great hump by class name, small hump by variable name
    • The keyword yield has been added, so use the yield method with inverted quotes such as Thread.yield
  • Keyword
  • Notes
    • Compatible with java annotations and supports the nested structure of annotations
  • Line Break
    • You can use the end of a semicolon or the end of a carriage return. Note that multiple commands must be separated by semicolons
  • Introducing packages
    • Introduce a single class: import java.util.Date;
    • Introduce all classes under the package: import java.util.;
    • Introduce several classes (selectors) under the package: import java.util.{Date,HashSet,HashMap}
    • Rename after class introduction: import java.util. {Date => OldDate}
    • Hide some members under the package: import java.util. {Date=>,}
    • The default package imports are: java.lang., scala., Predef.. No package name is required for the use of the inner class of the default introduced package.

2. Data type

Note: All data is objects and there is no basic data type

  • Any: parent of all classes
  • AnyRef: Base class for all reference classes
  • AnyVal: Base class for all value types
  • Nothing: A subclass of all classes
  • Null: null reference
  • Unit: Null value, just like void in java
  • Nine Value Types (AnyVal)
    • Integer type
      • Byte
      • Short
      • Int
      • Long
    • float
      • Float
      • Double
    • Character
      • Char
    • Boolean
      • Boolean
    • empty
      • Unit
  • Data Type Diagram

 

3. Constants and variables

constant
Definition: A quantity that does not change during the course of a program is called a constant
Usage: Declare constants with val ue
variable
Definition: The amount of change that occurs during a program is called a variable
How to use: Use var to declare variables
Explicit declaration

var name:String = "mizui"
//Formula var or value variable name: variable type = value

Implicit declaration

var name = "mizui"
//Formula var or value variable name = value
//scala supports type inference, so it's convenient to write this

4. Access modifiers

  • Type:
    • private
    • protected
    • public
  • Differences from java:
    • The default access modifier is missing here
    • The default modifier for scala's object is public
  • private
    • Visible only inside the class
    • Note: In the case of nesting, the outer class cannot even access the private members of the inner class
  • protected
    • Stricter than java, accessible only to subclasses, inaccessible under the same package
  • public
    • Same as java
  • Scope Protection Mechanism
    • private[x], that is, "This member is private to all classes except the classes in [...] or the classes in [...] packages and their associated objects.
    • protected[x], that is, "This member is protected against all classes except the classes in [...] or the classes in [...] packages and their associated objects.

5. Operators

Include operator in 5

Arithmetic Operators


Relational Operators


Logical operators

 
Bitwise Operators


Assignment Operators


Operator Priority

 

6. Control statements

  • if ... else ...
    • Same as java
  • loop
    • while
      • Same as java
    • do ... while
      • Same as java
  • for
//Simple traversal
for(i <- 0 to 10) println(i)
//Output results are 0-10
//until keyword
for(i <- 0 until 10) println(i)
//Output results are 0-9
//by keyword
for(i <- 0 to 10 by 2) println(i)
//Output results 0,2,4,6,8,10
//Conditional Output
for(i <- 0 to 10 if(i%2==0)) println(i)
//Output results: 0,2,4,68,10
//Traversing a list of chains
var list = List(1,2,3)
for(x <- list) println(x)
//Output results: 1,2,3
//yeild keyword
var list2 = for(x <- list if(x%2==0)) yeild x
//The result is assigned to list2

7. Functions

scala's function is an object that can be passed as a parameter or return value
Define using val and def
Definition of function
Define Format

def functionName ([parameter list]) : [return type] = {
    function body
    return [expr]
}
  • Relevant Instructions
    • If the equals sign and method body are not written, the method is implicitly declared as an abstract method, and the type containing it is then an abstract type.
    • The return type can be any valid Cala data type, and if the function does not return a value, it can be returned as Unit, which is a Java-like void
  • call
    • Same as java
  • Advanced programming for functions (see: Advanced programming for scala-valued functions)
    • Call by Name
    • Specify parameter name call
    • Parameter Default
    • Variable length parameter
    • Recursive function
    • Higher order function
    • Nested Function
    • Anonymous function
    • Partial Application Function
    • currying

8. Closure

concept
         Closure is a function
The function calls an external variable during execution
Example

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))
    } 
}

9. Strings

concept
         Completely peer to java.lang.String
Variable String

var str = "hello"

Invariant String Builder

var str = new StringBuilder

Common Functions
         Get String Length
                length()
         String Connection
                + Or concat
         String formatting, similar to c
                printf()

10. Arrays

concept
         A sequential storage structure for storing elements of the same type
Use
         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);
    } 
}


Multidimensional Array

//This package needs to be introduced manually
import Array.ofDim;
//Create a 4x4 matrix
var myMatrix = ofDim[Int](4, 4)

 

Posted by balacay on Sat, 04 Dec 2021 09:58:51 -0800