Scala Series 1 - basic syntax

Posted by Tandem on Thu, 30 Sep 2021 04:25:33 +0200

1, Overview

1.Scala is a multi paradigm static type programming language. Scala supports object-oriented and functional programming
2.Scala source code (. scala) will be compiled into Java bytecode (. class), and then run on the JVM. You can call the existing Java class library to realize the seamless connection between the two languages

2, Build environment

Installing Scala for windows

Preparation: install JDK1.8 and configure environment variables

  1. Create a scala folder under drive c

  2. Double click the scala-2.11.12.msi installation package (the installation path should not have Chinese / spaces)

  3. Configuring environment variables for Scala

    C:\scala\bin
    
  4. Open cmd window

    C:\Users\Administrator>scala
    Welcome to Scala 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_181).
    Type in expressions for evaluation. Or try :help.
    
    scala>
    

REPL of Scala

Introduction: the scala command line window opened above is called REPL, which means read > evaluation - > Print - > loop, also known as interactive interpreter
Note: when you enter the scala instruction code in the command line window, the interpreter will read the instruction code ® And calculate the corresponding value (E), then print the result §, and then wait for the user to input the instruction (L).

Sketch Map:

Centos installing Scala

Preparation: install JDK1.8 and configure environment variables

  1. Upload the rpm installation package of scala

    [root@CentOS ~]# rpm  -ivh scala-2.11.12.rpm
    Preparing...                ########################################### [100%]
       1:scala                  ########################################### [100%]
    [root@CentOS ~]# scala
    Welcome to Scala 2.11.12 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_171).
    Type in expressions for evaluation. Or try :help.
    scala>
    

IDEA integration Scala

Click the install plugin from disk option in File > setting > plugins, select scala-intellij-bin-2018.3.6.zip, and restart the IDEA after the installation is successful.

Plug in download path: https://plugins.jetbrains.com/plugin/1347-scala/versions

Create a maven project, right-click the project, select Add Framework Support, and select Scala

Create a scala folder under src/main, right-click and select mark Directory as - > sources root

Create a Scala Class class in the scala directory, and pay attention to selecting Object

Provide a main function in the HelloWorld class, right-click Run to Run

package demo1

object HelloWorld {

  def main(args: Array[String]): Unit = {
    print("test")
  }
}

3, Variable

1. Declare variables

Scala declares variables in two ways, one with val and the other with var (variable).

val / var variable name: variable type = variable value.

var modified variable value can be changed, while val modified constant value cannot be changed, which is equivalent to the variable modified by final in Java.

val example:

scala> val a1 = 10
scala> a1 = 20(X)

var example:

scala> var a2 = 10
scala> a2 = 20(OK)

2. Data type

Scala language is a completely object-oriented language, so it does not distinguish between basic types and reference types. These types are objects, which we call common types.

Scala common types include seven numeric types: Byte, Char, Short, Int, Long, Float, Double, Boolean, and String.

data typedescribe
Booleantrue or false
Byte8-bit, signed
Short16 bit, signed
Int32-bit, signed
Long64 bit, signed
Char16 bit, unsigned
Float32-bit, single precision floating-point number
Double64 bit, double precision floating point number
StringIn fact, it is composed of Char array

Note: since the basic type data of Java is an object in Scala,

That means that the basic types of data in Java can call object methods in Scala.

scala> 1.toString

Compared with Java's type system, Scala is undoubtedly much more complex! It is this complex and changeable type system that makes the perfect integration of object-oriented programming and functional programming! In Scala, all values are class objects, and all classes, including value types, ultimately inherit from a unified root type, Any. Unified type is another feature of scala. More specifically, Scala also defines several bottom classes, such as Null and Nothing.

  • Null is a subtype of all reference types, and Nothing is a subtype of all types. The null class has only one instance object, null, which is similar to the null reference in Java. Null can be assigned to any reference type, but cannot be assigned to a value type.

  • Nothing can be used as the return type of a method without a normal return value. It intuitively tells you that this method will not return normally. Moreover, because nothing is a subclass of any other type, it can also be compatible with methods that require a return value.

  • The unit type is used to identify a procedure, that is, a function without an explicit return value. Thus, unit is similar to void in Java. Unit has only one instance, (), and this instance has no substantive meaning.

3. Value type conversion

  • Automatic type conversion

    Introduction: when Scala programs perform assignment or operation, types with low precision are automatically converted to data types with high precision. This is automatic type conversion

    Automatic lifting principle:The type of the expression result is automatically promoted to the largest type in the operand
     for example:
    var a1:Int = 10
    var a2:Double = 4.5
    var a3:Double = a1+a2
    
    (byte,short)and char There is no automatic conversion between, but byte,short,char Can be automatically converted to int type
    byte,short,char The three of them can be calculated and converted into int type
    var a3:Byte = 10
    var a4:Short = 20
    var a5:Int = a3 + a4  //ok
    a4 = a3 + a4  //error
    
  • Cast type

    Introduction: the inverse process of automatic type conversion, which converts data types with large capacity into data types with small capacity.
    Cast function should be added when using, but it may cause precision reduction or overflow. Pay special attention.

    java:    int i = (int)2.5;
    scala:   var num:Int = 2.5.toInt
    
  • Conversion of value type and string type

    Introduction: in program development, we often need to convert the basic data type to String type.
    Or convert String type to basic data type

    grammar: Value of basic type + ""
    var a2:String = 1 + ""
    
    grammar: Convert string to base type
    var s1:String ="12"
    var s2:Int = s1.toInt
    var s3:Byte = s1.toByte
    var s4:Short = s1.toShort
    var s5:Double = s1.toDouble
    var s6:Long = s1.toLong
    

4. Operator

  • Arithmetic operator (+ - * /%)

  • Comparison operator

  • Logical operator

  • Assignment Operators

Note: there are no + +, – operators in Scala. You need to use + =, - = to achieve the same effect.

No ternary operator

5. Console reception

import scala.io.StdIn

val i: Int = StdIn.readInt()
println(i)

4, Process control of procedures

Branch control

if else

if(condition){
  
}else if(condition){

}else{

}

for example:
var a=28
if(a<=10){
    println("child")
}else if(a<=18){
    println("boy|girl")
}else{
    println("man|woman")
}

Note: any expression in Scala has a return value, which means that the if else expression actually has a return result. The specific value of the return result depends on the last line of the code body that meets the conditions

var a1 = 0
var res = if(a1 == 0){
       "male"
}else{
       "female"
}
println(res)

If a judgment is missing, nothing is returned, but Scala thinks that any expression will have a value. For null values, use the Unit class, called a useless placeholder, which is equivalent to void in java, and the print result is (),

val result =
    if(sumVal > 20){
    "The result is greater than 20"
    }
println(result)

Expressions in Java have no values, so in order to make up for such defects, ternary operators appear, but they are not in Scala because they are not needed at all.

// Java
int result = flg ? 1 : 0
// Scala
val result = if (flg) 1 else 0

match (pattern matching)

Pattern matching in scala is similar to the switch syntax in java, but more powerful.
In the pattern matching syntax, the match keyword is used to declare, and each branch is declared with the case keyword. When matching is needed, it will start from the first case branch. If the matching is successful, the corresponding logic code will be executed. If the matching is unsuccessful, continue to execute the next branch for judgment. If all cases do not match, the case is executed_ Branch, similar to the default statement in java

Example 1: determine the value of opr variable

var opr = "A"
opr match {
      case "A"  => println("1")
      case "B"  => println("2")
      case "C"  => println("3")
      case _    => println("default")
}

Detail analysis
① If all case If they don't match, it will be executed case_branch,be similar to java Medium default sentence
② If all case They don't match and they don't write case_Branch, then it will be thrown out. MatchError abnormal
③ each case Yes, No break Statement, automatic interrupt case
④ Can be in match Use other types in, not just strings
⑤ => Equivalent to java switch of :
⑥ => The following code block to the next case,Is executed as a whole and can be used{}It can be expanded or not

Cycle control

While and do while loops

while(condition){
  //Circulatory body
  //Cyclic variable iteration  
}

do{
  //Circulatory body
  //Cyclic variable iteration  
}while(Cycle condition)

for loop

1. Range data cycle

for (i <- 1 to 10){   	 //Anterior posterior closure
	println(i)
}

for (i <- 1 until 10){    //Front closing and rear opening
	println(i)
}

2. Cycle guard

Features: circular guard, i.e. circular protection type(Also known as conditional judgment,guard). The protective type is true Then it enters the circulation body,by false
 Skip
for (i <- 1 to 10;if i%2 ==0){
     println(i)
}
 
Equivalent to
for (i <- 1 to 10){
   if (i%2 ==0){
      println(i)
  }
}

3. Nested loop

for (i <- 1 to 2;j <- 1 to 3){
        println("i="+i+"  j="+j)
}
Output results:
i=1  j=1
i=1  j=2
i=1  j=3
i=2  j=1
i=2  j=2
i=2  j=3


Equivalent to
for (i <- 1 to 2){
    for(j <- 1 to 3){
        println("i="+i+"  j="+j)
    }
}

4. Cycle return value

var res = for(i <- 1 to 10 ) yield i
println(res)

Function: returns the results processed during traversal to a new Vector In collection,i Here is a code block,That means we can i Process
 Output results:  Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Break & Continue

Scala's built-in control structure removes break and continue

① It is recommended to use the functional style to solve the function of break, rather than a keyword

import scala.util.control.Breaks

//breakable is a high-order function (the function that can receive the function is a high-order function)
//breakable handles the exception thrown by break(), and the code continues to execute
//When we pass in a code block, the scala programmer changes () to {}
Breaks.breakable{
    for(i<- 1 to 9){
        if(i == 5){
          Breaks.break()
        }
        println(i)
	}
}
println("end")


Output results:	0	1	2	3	4	end

② You can use if - else or loop guard to implement the effect of continue

for(i <- 0 until 9 ; if ( i != 5 && i != 8) ){
      println(i)
}
 println("end")

5, Functions

The standard format of scala defined functions is:

def Function name(Parameter name 1: Parameter type 1, Parameter name 2: Parameter type 2) : Return type = {
  Function body
}

1) Function has a return value

def f1() : String= {
  return "f1"
}

Note: functions in scala can infer the return value type of the function by themselves according to the last line of code in the function body. In this case, the return keyword can be omitted. Since Scala can infer by itself, the return value type can also be omitted when the return keyword is omitted.
If the function explicitly uses the return keyword, the function cannot omit the return value type.

2) Function has no return value

def f2() : Unit = {
  println("f2")
}

Note: if the function explicitly declares no return value (declares Unit), there will be no return value even if the return keyword is used in the function body.
If the explicit function has no return value or the return value type is uncertain, the return value type can be omitted

A function whose return type is Unit is called a procedure. If it is clear that the function has no return value, the equal sign can be omitted

3) Function has parameters

def f4(p: String) = {
  println(p)
}

Note: if the parameter list is not empty, then you need to pass the parameter when you call it, and you can not omit it. This is not the same as the JavaScript syntax. If you call a parameter in JavaScript, if the parameter is not passed, then the parameter will automatically assign undefined. Scala can also achieve a similar function, that is, when the parameter is declared, the initial value is directly assigned.

def f5(p:String = "f5") {
    println(p);
}

When calling a function, if no parameters are passed, the default initial value is adopted. If parameters are passed, the passed parameters will override the initialization.

f5() // Print f5 without parameters
f5("function") // Transfer parameters, override default values, print function

If the function has multiple parameters and each parameter can be set with a default value, it is uncertain whether the passed parameters overwrite the default value or are assigned to parameters without a default value (the default is in the order of declaration). In this case, a named parameter can be used

def f6 ( p1 : String = "v1", p2 : String ) {
    println(p1 + p2);
}
f6("v2" )  // (Error)
f6(p2="v2") // (OK)

4) Variable length parameter

Uncertain number parameters, similar to Java

def f7(args: Int*) = {
  var result = 0
  for(arg <- args)
    result += arg
  result
}

5) Inert function

When the return value of the function is declared lazy, the execution of the function will be delayed until we take this value for the first time. This function is called lazy function and lazy loading (lazy loading) in some Java framework code

 def f10(): String = {
    println("f10 Method execution")
    "ha-ha" 
 }
 lazy val msg = f10()
 println("f10 Method not executed")
 println(msg)

6) Embedded function

In scala, you can continue to define functions

def main(args: Array[String]): Unit = {
    def test1(): Unit ={
      println("test")
    }
    test1()
}

7) Anonymous function

1. You do not need to write the def function name

2. There is no need to write the return type and use type derivation

3. = become = >

4. If there are multiple lines, use {} include, otherwise it is recommended to omit

//Ordinary function
def test1(v1:Int,v2:Int):Int = {
    v1+v2
}

//Anonymous function
(v1:Int,v2:Int) => v1+v2

//In scala, a function is also a value, so you can use variables to store anonymous functions
val f1 = (v1:Int,v2:Int) => v1+v2
f1(10,20)     //Output result: 30

8) Functions can be used as arguments

In scala, if the parameter or return value of a function is a function, the function can be called a high-order function

def main(args: Array[String]): Unit = {
    val i: Int = test1((a1,a2)=>a1-a2,10,20)
    println(i)
}

def test1(f1:(Int,Int)=>Int,v1:Int,v2:Int)={
    f1(v1,v2)
}

9) Function can be used as a return value

def main(args: Array[String]): Unit = {
    val f1: (Int, Int) => Int = test1()
    f1(10,20)
}

def test1():(Int,Int)=>Int ={
    (x:Int,y:Int)=>x+y
}

Topics: Java Scala