scala foundation related

Posted by bdichiara on Fri, 14 Jan 2022 17:08:21 +0100

About Scala

  1. Scala is developed on the basis of Java and runs on the Java virtual machine

  2. The syntax structure of Scala is similar to the combination of Java and python

    • If there is only one statement in a line, the semicolon can not be added at the end of the line
    • Unlike Java, Scala can define global functions independently of classes
  3. There is no static keyword in Scala

  4. Scala takes the main function in the object class as the program entry, such as:

     object HelloWorld{
         def main(args:Array[String]):Unit={
             println("hello world")
         }
     }
    

data type

  1. Scala provides the following basic data types:
    • Int
    • Float
    • Double
    • String
    • Boolean
    • Unit: represents no value, which is the same as void in Java. It is used as the result type of the method that does not return any results
  2. Like python, data types in Scala are objects
  3. Scala has a garbage collection mechanism

Constants and variables

constant
  1. Scala defines constants using the val keyword in the definition format: val name[:type]=initialization

    • Options in brackets, such as:

      val v1 : Int = 5
      val v2 = 6 // <==> val v2 : Int = 6
      
variable
  1. Variables defined in Scala use the VaR keyword. The definition format is var name[:type]=initialization

    • Similar to defining constants, options are in brackets, such as:

      var v : Int = 5
      var vv = 10 // <==> var vv : Int = 10
      
Naming conventions
  1. Variables and constants in Scala are required to start with letters or underscores, followed by more letters, numbers and underscores

operator

  1. Arithmetic operator: + - * /%
  2. Relational operator: > < > = < = ==
  3. Logical operator: & & |!
  4. Bitwise operators: &|^
  5. Assignment operator: = + = - = * = / =% = < = > = & = | =^=
  6. There are two call formats for operators in Scala. One is common, like a + b, and the other is a+ (b)
    • It is expressed as a Operator (b)

container

Array array
  1. An array is a fixed size sequential collection that stores elements of the same type

  2. The syntax for declaring arrays in Scala is as follows:

    • var arr:Array[String] = new Array[String](length)

    • var arr = Array(elem1, emem2, ...)

    • For example, declare an immutable array with a length of 3 and assign a value

       val arr:Array[String] = new Array[String](3)
       arr(0) = "this"; arr(1) = "that"; arr(2) = "there";
       	// Scala arrays use () to access elements through subscripts
       val arr2 = Array("this", "that", "there")
      
    • You can also use the range() method to create an isometric array, which requires import Array_

        import Array._
        var arr = range(1,10,2) // range is the same as python
      
  3. Common methods of array:

    • arr.length returns the length of the array
    • arr.head view the first element of the array
    • arr.tail view the elements in the array except the first element
    • arr.isEmpty determines whether the array is empty
    • arr.contains(x) determines whether the array contains element X
    • Note: if the class method is called in Scala, if there is no parameter, the brackets must be omitted.
      • For example, arr.head() must be written as arr.head
  4. To connect two arrays, you can use the operator + +, or you can use the function concat()

    • Before using the concat method, you need to use import Array_ Import package first

      var arr1 = Array(1,2,3)
      var arr2 = Array(4,5,6)
      var arr3 = arr1 ++ arr2
      import Array._
      var arr4 = concat(arr1, arr2)
      
  5. Scala creates immutable arrays by default

    • Immutability here means that the array itself is immutable, that is, it cannot point to other arrays, and the internal elements can still be changed

    • To create a variable array, you need to import the package import Scala collection. mutable. ArrayBuffer

List list
  1. All elements of the list have the same type

  2. Unlike arrays, the elements of a list are immutable

  3. The declaration syntax of the list is as follows

    • var lis : List[type] = List(elem1,elem2,...)

      val lis : List[String] = List("this","that","there")
      val lsi2 : List[Int] = List(1,2,3,4)
      val lis3 : List[Nothing] = List()
      
    • var lis : List[type] = elem1 :: elem2 :: ... :: Nil

    • :: and nil are the two basic units for constructing a list. Nil represents an empty list and:: is an infix operator, indicating that the list extends from the front end and follows the right combination

      val lis : List[String] = "this" :: "that" :: "there" :: Nil
      val lis2 : List[Int] = 1 :: 2 :: 3 :: Nil
      val lis3 : List[Nothing] = Nil
      
  4. Common methods of listing:

    • lis.head gets the first element
    • lis.init returns all elements except the last one
    • lis.last gets the last element
    • lis.tail returns all elements except the first one
    • lis.:::(prefix:List[A]) adds the elements of the specified list at the beginning of the list
      • Used to merge two lists, such as lis1:::lis2 or lis1.:::(lis2)
      • You can also use the concat method, such as list concat(lis1, lis2)
    • lis.take(n:Int) gets the first n items in the list
    • lis.contains(x) determines whether element X is in the list
Set set
  1. All elements in a collection are unique compared to a list.

  2. Collections are declared as follows

    • val st : Set[type] = Set(elem1, elem2, ...)

      val sst : Set[Int] = Set(1,2,3,4,5,5,5)
      
  3. Common methods of collection:

    • st.head gets the first element
    • st.init returns all elements except the last one
    • st.last returns the last element
    • st.tail returns all elements except the first one
    • St. + + (elements: set [a]) merges two sets
      • Same as array, different from list
    • st.take(n:Int) gets the first n elements of the list
    • st.contains(x:A) determines whether x is in the set
  4. Scala creates immutable collections by default

    • To create a variable collection, you need to import the package import Scala collection. mutable. Set
Map map
  1. Mapping is an iterative key value pair structure. All values can be obtained through keys, and the key value is unique

  2. The syntax of declaration mapping is as follows:

    • val mp : Map[type1,type2] = Map(key1->value1,key2->value2,...)

      val person : Map[String,Int] = Map("jhon"->34,"joe"->22)
      
  3. Common methods of mapping:

    • The common methods of collection are basically the same as mapping. Here are different methods
    • mp.isEmpty determines whether the mapping is empty
    • mp.keys returns all keys
    • mp.values returns all values
Tuple Tuplen
  1. Tuple is a structure similar to list, but different from list, tuple can contain different types of elements, and the value of tuple is composed of a single value in parentheses

  2. Tuple declaration syntax is as follows

    • val tp = TupleN(elem1,elem2,elem3)

      • Tuple here is the tuple keyword, and N is the length of the specified tuple
    • val tp = (elem1, elem2, elem3)

      • Here, elem1, elem2 and elem3 belong to different types
      val tp1 = Tuple3(1, 3.14, "this") // Triplet
      val tp2 = (1, 3.14, "this") // ditto
      var tp3 = Tuple4("that", 1, 2.5, "this") // Quadruple
      
  3. The maximum length of tuples in Scala is 22, that is, it can contain up to 22 elements

  4. Tuples can be accessed by tuple names_ Element index, index starts from 1

     val tp = Tuple3(1, 3.14, "this")
     tp._1 // Access first element 1
     tp._2 // Access the second element 3.14
     tp._3 // Access the third element "this"
    

if branch

  1. if
    • if(condition){...}
  2. if...else
    • if(condition){...}
    • else {...}
  3. if...else if...else
    • if(condition){...}
    • else if (condition) {...}
    • else {...}
  4. if...>if
    • if(condition){if(condition){}}

loop

  1. while

    • example:

      var n = 5
      while(n > 0){
          n -= 1
      }
      
  2. do...while

    • example:

      var n = 5
      do{
       n -= 1
      }while(n >= 0)
      
  3. for

    • for (variable <- Set) {...}

      • Set could be:
        • a to b // include b
        • a until b // do not include b
        • st // st is a Set
    • example:

      for (var i <- 1 to 10){
       println(i)
      }
      for (var i <- 1 until 10){
       println(i)
      }
      var st : Set[Int] = Set(1,3,5,7,9)
      for (var i <- st){
       println(i)
      }
      
  4. multiple for

    • for (v1 <- Set1 ; v2 <- Set2){...}

      • <==> for (v1 <- Set1){ for (v2 <- Set2) {...} }
    • example:

     for (var i <- 1 to 10; var j <- 1 to i){
         print(i*j)
     }
     // equivalent to below:
     for (var i <- 1 to 10){
         for (var j <- 1 to i){
             print(i*j)
         }
     }
    

function

Ordinary function
  1. definition:

    • def funName(para1:type1,para2:type2,...)[:returnType]={...}

    • example:

      def fun1(a:Int, b:Int):Unit={
       print(a + b)
      }
      def fun2(a:Int, b:Int):Int={
       return a + b
      }
      def fun3(a:Int, b:Int)={
       return a + b
      }
      // fun3 is equivalent to below
      def fun4(a:Int, b:Int)={a + b}
      // 'return' could be ignored
      
Anonymous function
  1. definition:

    • Anonymous functions are defined with = >

    • (para1:type1,para2:type2,...)=>functionBody

    • For example:

      (x:Int, y:Int) => x + y
      g = (x:Int, y:Int) => x + y
      
    • Anonymous functions can also be used_ Define

    • For example:

      val add = (_:Int) + (_:Int)
      
      • When using this method to define anonymous functions, you should ensure that each parameter is used only once
Functions as arguments

1. A function as a parameter is defined in the same way as a general function, but it has at least one formal parameter in the form of a function

  1. For example:

    def fun(f:(Int,Int)=>Int,a:Int,b:Int):Unit={
        fun(a,b)
    }
    // call the function like
    val g = (x:Int, y:Int) => a+b
    fun(g, 1, 2)
    
Function as a function of return value
  1. A function as a return value is defined in the same way as a general function, but its return value is another function.

  2. For example:

    def fun(x:Int)={
        return (y:Int)=>x+y
    }
    // call the function like
    val g = fun(5)
    g(10)
    
Function coritization
  1. Function corrilization refers to splitting a function that calls multiple parameters at one time into a function that calls one parameter multiple times

  2. For example:

    def add(x:Int, y:Int):Int={return a+b}
    // Corellization is defined as
    def add2(x:Int)(y:Int):Int={return a+b}
    

Function combiner

  1. map

    • map is a function that takes out each element from a sequence and returns a new sequence after it is processed by a user-defined function. The number of elements in the new sequence is the same as the original

    • In scala, map is a class method

    • The map operation does not affect the original data

    • For example:

      val num : List[Int] = List(1,2,3,4,5)
      num.map((x:Int)=>x*2)
      	// will get List(2,4,6,8,10)
      
  2. foreach

    • The same as map, but foreach does not return a value. It just takes all the elements in the sequence out of the sequence one by one for processing.

    • Similarly, foreach is also used as a class method

    • foreach also does not affect the original data

    • For example:

      val num : List[Int] = List(1,2,3,4,5)
      num.foreach((x:Int)=>x*2)
      	// will get nothing
      num.foreach((x:Int)=>print(x*2))
      	// will display 2 4 6 8 10
      
  3. filter

    • filter needs a function that returns boolean type as a parameter, takes out all elements in the sequence in turn and puts them into the function for judgment, and only retains the sequence composed of elements with return value of true

    • The filter will affect the original data

    • For example:

      val num : List[Int] = List(1,2,3,4,5)
      num.filter(x=>x%2==0) // remove odd number
      	// num will be List(2,4)
      
  4. flatten

    • Flatten is used to flatten the sequence, flattening the high-dimensional sequence into one dimension.

    • flatten will affect the original data

    • For example:

      val lis = List(List(1,2,3),List(4,5))
      list.flatten
      	// lis will be List(1,2,3,4,5)
      
  5. flatMap

    • flatMap is a combination of flat and map It takes a function that processes nested sequences as parameters and returns a 1-dimensional sequence composed of elements processed by the function

    • flatMap will affect the original data

    • For example:

      val num = List(List(1,2,3),List(4,5))
      num.flatMap(x=>x.map(_*2))
      	// num will be List(2,4,6,8,10)
      // is like below
      num = num.map(x=>x*2)
      num.flatten
      
  6. groupBy

    • groupBy receives a function that returns boolean type as a parameter, groups all elements of the sequence through this function, and the return value is Map type

    • groupBy does not affect the original data

    • For example:

      val num : List[Int] = List(1,2,3,4,5,6)
      num.groupBy(x=>x%2==0)
      	// will get Map(false->List(1,3,5),true->(2,4,6))
      

Classes and objects

Class definition
  1. Use the class keyword to define a class. The syntax is as follows

    • class className[(para1, para2,...)][extends base]{...}
  2. Class can have parameters for class member initialization

  3. Class inherits using the extends keyword

    • Like Java, Scala only supports inheriting one parent class
    • The override keyword is required for subclasses to override the implemented methods of the parent class
    • The subclass overrides the abstract method that the parent class does not implement, and the override keyword is not used
    • Like Java, abstract classes use the keyword abstract
  4. For example:

    abstract class Base{
        def sayhello:Unit={
            println("hello")
        }
        def saysome(some:String) : Unit;
    }
    class MyClass(x:Int, y:Int)extends Base{
        var xl:Int = x
        var yl:Int = y
        override def sayhello:Unit={
            println("HELLO!")
        }
        def saysome(some:String) : Unit = {
            println(some)
        }
    }
    
Singleton class
  1. There is no static keyword in Scala, so there is no static member. Scala uses the object class to implement the singleton mode

  2. Use object to define a singleton object. There is only one instance in the whole program. The object object cannot carry parameters

  3. The definition syntax is as follows

    • object objectName{...}
  4. The main function in the object object will be used as the entry of the program

  5. When an object has the same name as a class in the same file, the object is called the associated object of class and the class is called the associated class of object. Private members can be accessed from each other

  6. as

    object MyClass{
        def main(args:Array[String]):Unit={
            println(MyClass.info)
        }
    }
    class MyClass{
        private val info:String = "this"
    }
    
Scala pattern matching
  1. Scala pattern matching mechanism is defined by a special function and matched to different execution schemes through the passed parameters, such as switch in Java

  2. as

    def matchTest(X:Int) = x match {
        case 1 => println("one")
        case 2 => println("two")
        case _ => println("other")
    }
    
  3. Each case in pattern matching does not need to break, and the matching ends automatically after the case is executed. There is no break keyword in Scala

  4. Pattern matching can also be used in lists and can be queried online

File reading and writing

Name, object is called the associated object of class, and class is called the associated class of object. Private members can be accessed from each other

  1. as

    object MyClass{
        def main(args:Array[String]):Unit={
            println(MyClass.info)
        }
    }
    class MyClass{
        private val info:String = "this"
    }
    
Scala pattern matching
  1. Scala pattern matching mechanism is defined by a special function and matched to different execution schemes through the passed parameters, such as switch in Java

  2. as

    def matchTest(X:Int) = x match {
        case 1 => println("one")
        case 2 => println("two")
        case _ => println("other")
    }
    
  3. Each case in pattern matching does not need to break, and the matching ends automatically after the case is executed. There is no break keyword in Scala

  4. Pattern matching can also be used in lists and can be queried online

Topics: Scala