Scala basic syntax

Posted by tijger on Sun, 09 Jan 2022 11:29:40 +0100

Scala is a static type programming language that takes Java virtual machine (JVM) as the running environment and combines the best features of object-oriented and functional programming (static languages need to be compiled in advance, such as Java, c, c + +, and dynamic languages such as js).

1) Scala is a multi paradigm programming language. Scala supports object-oriented and functional programming. (multi paradigm means multiple programming methods. There are four programming methods: process oriented, object-oriented, generic and functional.)

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.

3) As a single language, Scala is very concise and efficient.

4) When designing Scala, Martin odesky referred to the design idea of Java. It can be said that Scala originated from Java. At the same time, Martin odesky also added his own idea to integrate the characteristics of functional programming language into Java,

Therefore, students who have studied Java can quickly master Scala as long as they understand the similarities and differences between Scala and Java in the process of learning Scala.

 

 

Scala is completely object-oriented, so Scala removes non object-oriented elements in Java, such as static keyword and void type

1) static Scala has no static keyword. object implements functions similar to static methods (class name. Method name).

2) void for functions that have no return value, Scala defines the return value type as the Unit class

 

Official programming guide 1)

View online: https://www.scala-lang.org

 

Scala annotations use exactly the same as Java.

(1) single line notes://

(2) Multiline comment: / **/

(3) Document comments: / * * **/

 

Code specification

(1) Use a tab operation to indent. By default, the whole moves to the right and shift+tab moves to the left

(2) Or use ctrl + alt + L to format

(3) Operator is habitually added with a space on both sides. For example: 2 + 4 * 5.

(4) The maximum length of a line shall not exceed 80 characters. If it exceeds, please use newline display to keep the format elegant as far as possible

 

Variables and constants (emphasis)

0) review:

Java variable and constant syntax

Variable type variable name = initial value int a = 10

Final constant type constant name = initial value final int b = 20

1) Scala variable and constant syntax

Var variable name [: variable type] = initial value var i:Int = 10

val constant name [: constant type] = initial value val j:Int = 20

Note: variables are not used where constants can be used

 

(1) When declaring a variable, the type can be omitted and the compiler deduces automatically, that is, type derivation

(2) After the type is determined, it cannot be modified, indicating that Scala is a strong data type language.

(3) Variable declaration must have an initial value

(4) When declaring / defining a variable, you can use var or val to modify it. The variable modified by var can be changed, and the variable modified by val cannot be changed.

 

def main(args: Array[String]): Unit = {
 //(1)When declaring a variable, the type can be omitted and the compiler deduces automatically, that is, type derivation
 var age = 18
 age = 30
 //(2)After the type is determined, it cannot be modified. Description Scala Is a strongly data typed language.
// age = "tom" // error
 //(3)Variable declaration must have an initial value
// var name //error
//(4)In statement/When defining a variable, you can use var perhaps val To decorate, var modification
The variable can be changed, val Modified variables cannot be modified.
 var num1 = 10 // variable
 val num2 = 20 // Immutable
 num1 = 30 // correct
 //num2 = 100 //Error because num2 yes val Embellished
 }

(5) The object reference modified by var can be changed, while the object modified by val cannot be changed, but the state (value) of the object can be changed. (for example, custom objects, arrays, collections, etc.)

object TestVar {
 def main(args: Array[String]): Unit = {
 // p1 yes var Decorated, p1 The properties of can be changed, and p1 It can change itself
 var p1 = new Person()
 p1.name = "dalang"
 p1 = null
 // p2 yes val Decorated, then p2 Itself is immutable (i.e p2 The memory address of cannot be changed,
But, p2 The properties of can be changed because they are useless val modification.
 val p2 = new Person()
 p2.name="jinlian"
// p2 = null // Wrong, because p2 yes val Embellished
 }
}
class Person{
 var name : String = "jinlian"
}

 

 

Naming conventions for identifiers

The character sequence used by Scala when naming various variables, methods, functions, etc. is called an identifier. That is: any place where you can name yourself is called an identifier.

1) Naming rules the identifier declaration in Scala is basically the same as that in Java, but the details will change. There are three rules:

(1) Begin with a letter or underscore followed by letters, numbers, and underscores

(2) Starts with an operator and contains only operators (+ - * / #! Etc.)

(3) Use back quotation marks` Any string included, even Scala keywords (39) can be used

 

String output

1) Basic grammar

(1) String, connected by + sign

(2) printf usage: string, passing value through%.

(3) String template (interpolation string): get variable value through $

object test {
  def main(args: Array[String]): Unit = {
    var name: String = "jinlian"
    var age: Int = 18
    //(1)String, by+Number connection
    println(name + " " + age)
    //(2)printf Usage string, by%Pass value.
    printf("name=%s age=%d\n", name, age)
    //(3)String, by $quote
    //Multiline string, in Scala It can be realized by enclosing multiple lines of string with three double quotes.
    //Input content with spaces\t And so on, resulting in the beginning position of each line can not be neatly aligned.
    //application scala of stripMargin Method, in scala in stripMargin default
    //Yes“|"As a connector,//Add a before the line header of a multiline wrap“|"Just use the symbol.
    val s =
      """
      |select
      |name,
      |age
      |from user
      |where name="zhangsan"
 """.stripMargin
    println(s)

    //If you need to operate on a variable, you can add ${}
    val s1 =
      s"""
         |select
         | name,
         | age
         |from user
         |where name="$name" and age=${age+2}
 """.stripMargin
    println(s1)
    val s2 = s"name=$name"
    println(s2)
  }
}

 

keyboard entry

In programming, if you need to receive the data input by the user, you can use the keyboard to input statements to obtain it.

def main(args: Array[String]): Unit = {
    // 1 Enter name
    println("input name:")
    var name = StdIn.readLine()
    // 2 Enter age
    println("input age:")
    var age = StdIn.readShort()
    // 3 Enter salary
    println("input sal:")
    var sal = StdIn.readDouble()
    // 4 Print
    println("name=" + name)
    println("age=" + age)
    println("sal=" + sal)
  }

 

Shift Bitwise Operators

a is 60

< < move left operator a < < 2 output result 240, binary interpretation: 0011 0000 > >

Move right operator a > > 2 output result 15, binary interpretation: 0000 1111

 

Scala operator essence

In fact, there are no operators in Scala. All operators are methods.

1) When an object's method is called, click Can be omitted

2) If there is only one function parameter or no parameter, () can be omitted

def main(args: Array[String]): Unit = {
 // Standard addition operation
 val i:Int = 1.+(1)
 // (1)When an object's method is called,.Can be omitted
 val j:Int = 1 + (1)
 // (2)If the function has only one parameter or no parameter,()Can be omitted
 val k:Int = 1 + 1
}

 

 

Process control

There are three kinds of branch control: single branch, double branch and multi branch

//Single branch
if
(Conditional expression) { Execute code block }

//Double branch
if (Conditional expression) { Execute code block 1 } else { Execute code block 2 }

//Multi branch
if (Conditional expression 1) { Execute code block 1 } else if (Conditional expression 2) { Execute code block 2 } ...... else { Execute code block n }

 

It is worth noting that the if else expression in Scala actually has a return value. The specific return value depends on the last line of the code body that meets the conditions

def main(args: Array[String]): Unit = {
 println("input age")
 var age = StdIn.readInt()
 val res :String = if (age < 18){
 "childhood"
 }else if(age>=18 && age<30){
 "middle age"
 }else{
 "old age"
 }
 println(res)
 }

 

Switch branch structure

In Scala, there is no Switch, but pattern matching.

 

For cycle control

Scala also provides many features for the common control structure of the for loop. These features of the for loop are called for derivation or for expression.

 

Range data cycle (To)

for(i <- 1 to 3){
 print(i + " ")
}
println()
//(1)i A variable representing a loop,<- regulations to
//(2)i Will start from 1-3 Cycle, front and rear closing

 

Range data cycle (Until)

for(i <- 1 until 3) {
 print(i + " ")
}
println()
//(1)The difference between this method and the previous one is i It's from 1 to 3-1
//(2)Even if the front is closed and the rear is open

 

Cycle guard

for(i <- 1 to 3 if i != 2) {
 print(i + " ")
}
println()
//(1)Circular guard, i.e. circular protection type (also known as conditional judgment type, guard). The protective type is true //Enter the inside of the circulating body, and false Skip, similar to continue. 

The above code is equivalent

for (i <- 1 to 3){
if (i != 2) {
print(i + " ")
}
}

 

Cycle step

for (i <- 1 to 10 by 2) {
 println("i=" + i)
}
//explain: by Represents the step size

//Output results
i=1
i=3
i=5
i=7
i=9

 

Nested loop

for(i <- 1 to 3; j <- 1 to 3) {
 println(" i =" + i + " j = " + j)
}
//Note: there is no keyword, so it must be added after the range; To block logic

The above code is equivalent to

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

 

Introducing variables

for(i <- 1 to 3; j = 4 - i) {
 println("i=" + i + " j=" + j)
}
//(1)for When there are more than one expression in a row of the derivation, it should be added ; To block logic
//Note the distinction between nested loops and nested loops j And i It doesn't matter, and in this cycle, j Is based on i From the value of

There is an unwritten Convention for the for derivation: when the for derivation contains only a single expression, parentheses are used. When multiple expressions are included, there is usually one expression per line, and curly braces are used instead of parentheses, as shown below

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

The above code is equivalent to

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

 

Loop return value

val res = for(i <- 1 to 10) yield i
println(res)
//Description: return the results processed in the traversal process to a new Vector Collection, using yield keyword.
//Note: it is rarely used in development.

 

While and do While loop control

(1) A loop condition is an expression that returns a Boolean value

(2) A while loop is a statement that is judged before execution

(3) Unlike the for statement, the while statement does not return a value, that is, the result of the entire while statement is of type Unit ()

(4) Because there is no return value in while, it is inevitable to use variables when using this statement to calculate and return results, and variables need to be declared outside the while loop, which is equivalent to the internal of the loop and affects the external variables. Therefore, it is not recommended to use, but to use the for loop.

 

Cycle interrupt

Scala's built-in control structure specifically removes break and continue in order to better adapt to functional programming. It is recommended to use functional style to solve the functions of break and continue, rather than a keyword.

The breakable control structure is used in Scala to implement break and continue functions.

import scala.util.control.Breaks
def main(args: Array[String]): Unit = {
 Breaks.breakable(
 for (elem <- 1 to 10) {
 println(elem)
 if (elem == 5) Breaks.break()
 }
 )
 println("Normal end of cycle")
}


//: yes break Omit,Pay attention to the different objects of the guide
import scala.util.control.Breaks._
object TestBreak {
 def main(args: Array[String]): Unit = {
 
 breakable {
 for (elem <- 1 to 10) {
 println(elem)
 if (elem == 5) break
 }
 }
 
 println("Normal end of cycle")
 }
}

 

//: Loop through all data within 10, odd print and even skip( continue)
object TestBreak {
 def main(args: Array[String]): Unit = {
 for (elem <- 1 to 10) {
 if (elem % 2 == 1) {
 println(elem)
 } else {
 println("continue")
 }
 }
 }
}

 

The above summary is based on Scala notes

Topics: Scala