[Big Data] Scala Quick Learning Manual 2

Keywords: Big Data Scala Session Java

Scala Quick Learning Manual 2

Category 1, Object, Inheritance, Characteristics

Category 1.1

Definition of Class 1

//In Scala, classes do not need to be declared public.
//Scala source files can contain multiple classes, all of which have public visibility.
class Person {
  //The variable modified with val is a read-only property with getter but not setter
  //(equivalent to variables modified with final in Java)
  val id = "9527"

  //Variables modified with var have both getter and setter
  var age: Int = 18

  //Class private fields, which can only be used inside a class
  private var name: String = "Tang Bohu"

  //Object private fields, access rights are more stringent, Person class methods can only access the field of the current object
  private[this] val pet = "Cockroach"
}

Class 2 constructors
Note: The main constructor executes all statements in the class definition

/**
  *Each class has a primary constructor whose parameters are placed directly after the class name and intertwined with the class.
  */
class Student(val name: String, val age: Int){
  //The main constructor executes all statements in the class definition
  println("Execute the main constructor")

  try {
    println("read file")
    throw new IOException("io exception")
  } catch {
    case e: NullPointerException => println("Print exception Exception : " + e)
    case e: IOException => println("Print exception Exception : " + e)
  } finally {
    println("implement finally Part")
  }

  private var gender = "male"

  //Defining Auxiliary Constructors with this Keyword
  def this(name: String, age: Int, gender: String){
    //Each auxiliary constructor must begin with a call to the main constructor or to other auxiliary constructors
    this(name, age)
    println("Execution Auxiliary Constructor")
    this.gender = gender
  }
}



/**
  *Constructor parameters can be used by at least one method without val or var.
  *Then it will be promoted to a field.
  */
//Private after the class name becomes private
class Queen private(val name: String, prop: Array[String], private var age: Int = 18){
  
  println(prop.size)

  //When prop is used by the following method, it becomes an immutable object private field, equivalent to private[this] val prop
  //If this parameter is not used by the method, it will not be saved as a field, just a common parameter that can be accessed by the code in the main constructor.
  def description = name + " is " + age + " years old with " + prop.toBuffer
}

object Queen{
  def main(args: Array[String]) {
    //Private constructors, used only in their associated objects
    val q = new Queen("hatano", Array("candle", "Whip"), 20)
    println(q.description())
  }
}

1.2 Objects

There are no static methods and static fields in Scala, but you can use the object grammar structure to achieve the same purpose.

  1. Storage tool methods and constants
  2. Efficient sharing of single immutable instances
  3. Singleton pattern
import scala.collection.mutable.ArrayBuffer


object SingletonDemo {
  def main(args: Array[String]) {
    //A singleton object, which does not need new, calls the method in the object with the class name. method
    val session = SessionFactory.getSession()
    println(session)
  }
}

object SessionFactory{
  //This part is equivalent to static blocks in java
  var counts = 5
  val sessions = new ArrayBuffer[Session]()
  while(counts > 0){
    sessions += new Session
    counts -= 1
  }

  //The method in object is equivalent to the static method in java
  def getSession(): Session ={
    sessions.remove(0)
  }
}

class Session{

}

2 Associated Objects

In Scala's classes, objects with the same class name are called associated objects, and private methods and attributes can be accessed between classes and associated objects.

class Dog {
  val id = 1
  private var name = "herry"

  def printName(): Unit ={
    //In the Dog class, you can access the private properties of the concomitant object Dog
    println(Dog.CONSTANT + name )
  }
}

/**
  * Companion Object
  */
object Dog {

  //Private Attributes in Associated Objects
  private val CONSTANT = "Wang Wang Wang : "

  def main(args: Array[String]) {
    val p = new Dog
    //Access private field name
    p.name = "123"
    p.printName()
  }
}

3 apply method

Usually, we define the application method in the concomitant object of the class, when we encounter the class name (parameter 1,... The apply method is called when the parameter n)

object ApplyDemo {
  def main(args: Array[String]) {
    //apply method of Array concomitant object is called
    //def apply(x: Int, xs: Int*): Array[Int]
    //There is only one element 5 in arr1
    val arr1 = Array(5)
    println(arr1.toBuffer)

    //new has a 5-length array containing five null s
    var arr2 = new Array(5)
  }
}

4 Application Objects

Scala programs must start with an object's main method, which can be extended by extending the App feature without writing the main method.

object AppObjectDemo extends App{
  //Do not write main method
  println("I love you Scala")
}

1.2 Inheritance

1 Extended Class

Extension classes in Scala use extends keywords as well as Java

2 Rewriting Method

override modifiers must be used to rewrite a non-abstract method in Scala

3 Type Check and Conversion

scala java
obj.isInstanceOf[C] obj instanceof C
obj.asInstanceOf[C] ©obj
classOf[C] C.class

Construction of Superclasses

object ClazzDemo {
  def main(args: Array[String]) {
    val h = new Human
    println(h.fight)
  }
}
//Similar interface
trait Flyable{
  def fly(): Unit ={
    println("I can fly")
  }

  def fight(): String
}

abstract class Animal {
  def run(): Int
  val name: String
}

class Human extends Animal with Flyable{

  val name = "abc"

  //How many times do you print "ABC"?
  val t1,t2,(a, b, c) = {
    println("ABC")
    (1,2,3)
  }

  println(a)
  println(t1._1)

  //Rewriting a non-abstract method in Scala must be modified with override
  override def fight(): String = {
    "fight with Stick"
  }
  //When overriding the abstract method of a superclass in a subclass, you don't need to use the override keyword, you can write it as well.
  def run(): Int = {
    1
  }
}

2 pattern matching and sample classes

Scala has a very powerful pattern matching mechanism, which can be applied to many occasions, such as switch statement, type checking and so on. And Scala also provides sample classes to optimize pattern matching so that it can match quickly.

2.1 Matched String

 import scala.util.Random

object CaseDemo01 extends App{
  val arr = Array("YoshizawaAkiho", "YuiHatano", "AoiSola")
  val name = arr(Random.nextInt(arr.length))
  name match {
    case "YoshizawaAkiho" => println("Miss Giza...")
    case "YuiHatano" => println("Mr. Bordeaux...")
    case _ => println("I don't know what you're talking about....")
  }
}

2.2 Matching Types

Note: case y: Double if (y >= 0) = >

Guard conditions can also be added to pattern matching. If it does not meet the guard requirements, it will fall into case uuuuuuuuuuuu

import scala.util.Random

object CaseDemo01 extends App{
  //val v = if(x >= 5) 1 else if(x < 2) 2.0 else "hello"
  val arr = Array("hello", 1, 2.0, CaseDemo)
  val v = arr(Random.nextInt(4))
  println(v)
  v match {
    case x: Int => println("Int " + x)
    case y: Double if(y >= 0) => println("Double "+ y)
    case z: String => println("String " + z)
    case _ => throw new Exception("not match exception")
  }
}

2.3 Matching Arrays, Tuples

Note: Lists in Scala are either empty (Nil denotes empty lists) or a head element plus a tail list.

9:: List (5, 2): The operator creates a new list of given headers and tails

Note: Operators are right-bound, such as 9:: 5:: 2:: Nil is equivalent to 9:: (5:: (2:: Nil)

object CaseDemo03 extends App{

  val arr = Array(1, 3, 5)
  arr match {
    case Array(1, x, y) => println(x + " " + y)
    case Array(0) => println("only 0")
    case Array(0, _*) => println("0 ...")
    case _ => println("something else")
  }

  val lst = List(3, -1)
  lst match {
    case 0 :: Nil => println("only 0")
    case x :: y :: Nil => println(s"x: $x y: $y")
    case 0 :: tail => println("0 ...")
    case _ => println("something else")
  }

  val tup = (2, 3, 7)
  tup match {
    case (1, x, y) => println(s"1, $x , $y")
    case (_, z, 5) => println(z)
    case  _ => println("else")
  }
}

2.4 Sample Class

In Scala, the sample class is a special class that can be used for pattern matching. case class is multi-instance, followed by construction parameters, case object is singleton

import scala.util.Random

case class SubmitTask(id: String, name: String)
case class HeartBeat(time: Long)
case object CheckTimeOutTask

object CaseDemo04 extends App{
  val arr = Array(CheckTimeOutTask, HeartBeat(12333), SubmitTask("0001", "task-0001"))

  arr(Random.nextInt(arr.length)) match {
    case SubmitTask(id, name) => {
      println(s"$id, $name")//Before you add s, $id takes the value of ID directly
    }
    case HeartBeat(time) => {
      println(time)
    }
    case CheckTimeOutTask => {
      println("check")
    }
  }
}

2.5 Option type

In Scala, Option type sample classes are used to represent values that may or may not exist (Option's subclasses are Some and None). Some wraps a value, and None means no value

object OptionDemo {
  def main(args: Array[String]) {
    val map = Map("a" -> 1, "b" -> 2)
    val v = map.get("b") match {
      case Some(i) => i
      case None => 0
    }
    println(v)
    //Better way
    val v1 = map.getOrElse("c", 0)
    println(v1)
  }
}

2.6 Partial Function

A set of case statements wrapped in curly brackets without matches is a partial function. It is an instance of Partial Function [A, B]. A represents the parameter type and B represents the return type. It is often used for input pattern matching.

object PartialFuncDemo  {

  def func1: PartialFunction[String, Int] = {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }

  def func2(num: String) : Int = num match {
    case "one" => 1
    case "two" => 2
    case _ => -1
  }

  def main(args: Array[String]) {
    println(func1("one"))
    println(func2("one"))
  }
}

Posted by blackcode on Fri, 25 Jan 2019 09:21:14 -0800