Scala study notes (1): basic articles

One, environment construction

For scala environment construction, please refer to Scala environment construction + IDEA plug-in installation and project creation


2. Features

2.1, static type

Scala does not allow variable types to be changed after declaration, and the types of all variables and expressions are fully determined at compile time.


2.2, strong type

Scala generally does not need to display the specified type when declaring a variable, the compiler will automatically infer the type .

There is no mandatory type conversion in Scala, but there are three ways to replace it:

  • Object name.asInstanceOf[XXX]
  • Object name.toXXX method
  • Implicit conversion (implicit keyword)

2.3, multi-paradigm programming

  • Object-oriented features
  1. All values ​​in Scala are objects
  2. Use companion objects to simulate class objects, and remove the static keyword (static properties and methods modified by static in Java are not pure objects)
  3. There is no interface, instead of classes and traits; using traits to achieve mixed-in multiple inheritance
  • Functional programming

    All functions are values, so you can use functions as parameters and return values


Three, data type

Insert picture description here
1. Value type (AnyVal)
(1) Store the value directly, and store its value on the stack
(2) Consistent with the eight basic types of Java (Byte, Short, Int, Long, Float, Double, Char, Boolean)
2. Reference type (AnyRef)
(1) Store the reference to its value, store the address on the stack, and store the value on the heap
(2) List, Option, etc., the class has been customized
3. Literal: The way to write constant values ​​directly in the code: 0, 0L, etc.; Symbol literal:'<identifier>', corresponding to scala.Symbol type
4. Special types:
(1) Null: all subclasses of reference types, there is only one instance object null, and null is the keyword
(2) Nothing: List() returns List[Nothing]
(3) Unit: only one instance object "()", a useless placeholder, similar to Java's void. All expressions have a value


Four, basic grammar

4.1, constants and variables

Variables: can be changed after assignment, and can be assigned multiple times during the life cycle

var 变量名称:类型 = xxx

Constant: cannot be changed after assignment, similar to final variables in Java

val 常量名称:类型 = xxx

4.2, keywords

Insert picture description here


4.3. Notes

object HelloWorld {
    
    
   /* 这是一个 Scala 程序
    * 多行注释
    */
   def main(args: Array[String]) {
    
    
      // 单行注释
      // 输出 Hello World
      println("Hello, world!") 
   }
}

4.4, line break

Scala is a line-oriented language. Statements can be terminated with a semicolon (;) or a newline character. If there is only one statement in a line, the semicolon is optional; if you write multiple statements in a line, you need a semicolon

val s = "换行"; println(s)

4.5、package

Scala uses the package keyword to define packages. There are two ways to define code in a package in Scala:

The first method is the same as Java. The package name is defined in the header of the file. This method puts all subsequent codes in the package

package scalatest
class HelloWorld

The second method, you can define multiple packages in one file

package scalatest {
    
    
  class HelloWorld 
}

4.6, reference package

Scala uses the import keyword to reference packages

import java.awt.Color  // 引入Color
 
import java.awt._  // 引入包内所有成员
 
def handler(evt: event.ActionEvent) {
    
     // java.awt.event.ActionEvent
  ...  // 因为引入了java.awt,所以可以省去前面的部分
}

The import statement can appear anywhere, not only at the top of the file. The effect of import extends from the beginning to the end of the statement block. This can greatly reduce the possibility of name conflicts.

If you want to introduce several members in the package, you can use selector (selector)

import java.awt.{
    
    Color, Font}
 
// 重命名成员
import java.util.{
    
    HashMap => JavaHashMap}
 
// 隐藏成员
import java.util.{
    
    HashMap => _, _} // 引入了util包的所有成员,但是HashMap被隐藏了

4.7, string interpolation

  1. s string interpolation, use $ to reference variables and expressions
object Test {
    
    
  def main(args: Array[String]): Unit = {
    
    
    var name = "Kyrie Irving"
    println(s"my name is $name")
    println(s"1+1=${1+1}")
  }
}

result
Insert picture description here

  1. f string interpolation, used to format the output
object Test {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val name = "Kyrie"
    val score = 57d
    println(f"$name%s got $score%.1f points")
  }
}

result
Insert picture description here

  1. Raw interpolation, shielding control effects such as escape characters
object Test {
    
    
  def main(args: Array[String]): Unit = {
    
    
    println(s"a\nb")
    println("----------")
    println(raw"a\nb")
  }
}

result
Insert picture description here


4.8. Condition control

  1. if和if…else…
	val x = 10
    if(x==10)println("x等于10")
    println("------------")
    if(x>10){
    
    
      println("x大于10")
    }else{
    
    
      println("x小于等于10")
    }

4.9, cycle control

  1. while loop
object Test {
    
    
  def main(args: Array[String]): Unit = {
    
    
    var a = 10
    while(a>=8){
    
    
      println(a)
      a = a-1
    }
  }
}
  1. do...while loop
object Test {
    
    
  def main(args: Array[String]): Unit = {
    
    
    var a = 10
    do{
    
    
      println(a)
      a = a + 1
    }while(a<=13)
  }
}
  1. for loop

The cycle conditions to and until both represent the interval, the to is before and after, and until is not before and after.

object Test {
    
    
  def main(args: Array[String]): Unit = {
    
    
    for(a <- 1 to 3){
    
    
      print(a+"\t")
    }
    for(a <- 1 until 3){
    
    
      print(a+"\t")
    }
  }
}
  1. for multiple loops-nine to nine multiplication table
def main(args: Array[String]): Unit = {
    
    
    for(i <- 1 to 9;j <- 1 to i){
    
    
      print(s"$j*$i=${i*j}\t")
      if(i==j)println()
    }
  }

Insert picture description here

  1. for loop filtering
def main(args: Array[String]): Unit = {
    
    
    for(i <- 1 to 10;if i%2==0;if i<9){
    
    
      print(i+"\t")
    }
  }

Insert picture description here

  1. Loop interruption
    There is no break statement in Scala language by default, and you need to import the package
    import scala.util.control.Breaks._

Source follows
Insert picture description here
case

import scala.util.control.Breaks._
    for(elem <- 1 to 4){
    
    
      print(6)
      if(elem%3==0){
    
    
        break()
      }
    }
  1. Loop return value
    The yield in the for loop will record the current element and save it in the collection, which will be returned to the collection after the loop ends. For derivation
def main(args: Array[String]): Unit = {
    
    
    var ret = for(i <- 1 to 10;if i%2==0;if i<9) yield i;
    for(j <- ret){
    
    
      print(j+"\t")
    }
  }

Insert picture description here


4.10, block expression

(1) A block expression is also a result, the structure of the last line in {} is the result of the block expression
(2) If the last line is an assignment statement, it is unit()

def main(args: Array[String]): Unit = {
    
    
    val myblock = {
    
    
      var x = 2
      var y = 3
      x+y
    }
    println(myblock)
  }

Insert picture description here

val myblock = {
    
    
      var x = 2
      var y = 3
      x = x+y
    }
    println(myblock)

Insert picture description here


Five, arrays, tuples, collections

5.1, array

  • Store fixed-size elements
  • Array index starts from 0
  • Generic use square brackets []
  • Array access uses parentheses ()
    Insert picture description here

5.2, tuple

  • Can contain different types of elements
  • Support up to 22 elements (Tuple1~Tuple22)
  • Except Tuple1, others can be created directly with ()
  • Use the underscore "_" to access the element, "_1" means the first element
    Insert picture description here
    Insert picture description here

Insert picture description here


5.3. Collection

Insert picture description here

1. Classification

  • Seq: Sequence, elements are arranged in order (List)
  • Set: set, the elements are not repeated
  • Map: Map, a collection of key-value pairs

All collections are inherited from Traversable, you can use the functions in it

2. Variable/immutable


  • Immutable collection scala.collection. immutable, immutable collection is selected in scala by default
    Insert picture description here
    Insert picture description here

  • Variable collection
    scala.collection. mutable, you can modify, add or remove elements of a collection
    Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_48482704/article/details/111885214