Install and configure the Scala environment

Note: Since Scala is based on the Java virtual Machine, you must have Java installed before using Scala, which we already have. There are three versions of Scala currently in use: 2.11, 2.12, and 2.13. At present, 2.12 is used more frequently, so we will use this version of Scala official website link: www.scala-lang.org/, download link: www.scala-lang.org/download/

After going to the appropriate version link, select the appropriate version for your computer system. Here, select Mac OX

www.scala-lang.org/download/2….

Configure environment variables (SCALA_HOME,PATH)

Refresh the source/etc/profile

Validation, enter Scala validation on the terminal

The Scala command line

The Scala command line, also known as the Scala interpreter (REPL), quickly compiles Scala code into bytecode, Then hand it over to the JVM to execute the REPL representation :Read -> Evaluation -> Print -> Loop

On the Scala command line, enter the Scala code and the interpreter returns the result. If you do not specify a variable to hold the computed value, the default value name will be the variable starting with RES and the number of results will be displayed

Such as:

scala> 1+1 
res0: Int = 2
Copy the code

You can continue to use the res0 variable and its values later

Such as:

scala> 5 * res0 
res1: Int = 10
Copy the code

Scala also has auto-completion on the command line, which makes it easy to use: type res, press TAB on the keyboard, and the current variable names start with res are listed below

scala> res
res0   res1
Copy the code

Basic use of Scala

variable

There are two types of variables in Scala: variable var and immutable val. Variable var: the value of a variable declared by var can be changed at any time. Immutable val: The value of a variable declared by val cannot be changed

Note: In practice, it is usually recommended to use val for variables whose values do not need to be changed, so that you do not have to worry about the value being incorrectly modified (equal to the Java final type). This can improve the stability and robustness of the system!

If you do not specify the type of the variable, Scala automatically deduces the type based on the value. Val c = 1 is equivalent to val c:Int = 1

The data type

There are two types of data types in Scala, basic data types and enhanced data types

The basic data types are: Byte, Char, Short, Int, Long, Float, Double, Boolean. The enhanced data types are: StringOps, RichInt, RichDouble, RichChar, etc

Scala uses these enhanced data classes to add hundreds of enhanced functionality to the base datatype. For example, RichInt provides a to function, 1.to(10), where Int is implicitly converted to RichInt before its to function is called

Notice that the to function can also be written like this

Using the basic data types, the corresponding function in RichInt can be called directly

The operator

Scala arithmetic operators and arithmetic operators of Java no difference Such as +, -, *, /, %, etc., and &, |, ^, > >, < < etc. Note: Scala provides no + + and – operators We can only use the + and – such as the count = 1, count++ is wrong, I have to write count plus = 1

If expression

In Scala, if expressions have a return value, which is the value returned by the last line of the if or else statement, unlike if expressions in Java, which do not return a value

For example: val age = 20; if (age > 18) 1 else 0

Here, because if expressions have a return value, you can assign if expressions to a variable

Since the if expression has a value, and the value of the if and else clauses may be of different types, what type is the value of the if expression?

Note :Scala automatically inferences and takes the common parent of both types

If (age > 18) “old” else 0 if(age > 18) “old” else 0 if(age > 18) if(age > 18) “old” else 0 Any is the public parent of String and Int

If not followed by an else, the default else value is Unit, which can also be represented by (), similar to void or null in Java. For example, val age = 12; If (age > 18) “old”. If (age > 18) “old” else (). The value of this expression is Any

What if I want to execute multiple lines of code in a Scala REPL? Use :paste and CTRL +D :paste starts the block and CTRL +D ends the block

Statement terminal

Scala does not require statement terminals by default. It treats each line as a statement. If you want to put multiple statements on a line, the preceding statement must use a statement terminal

scala> val age = 20; if(age > 18) 1 else 0 
age: Int = 20
res0: Int = 1
Copy the code

cycle

  • Print and println before we talk about loops, let’s look at the print commands print and println. Print does not use a newline, and println uses a newline, which is the same thing that print statements do in Java

  • What’s the difference between for in Scala and for in Java

“To” can be replaced with “until”

1 to 10 can retrieve all the numbers between 1 and 10. 1 until 10 can retrieve all the numbers between 1 and 9. Therefore, it is important to note that both “to” and “until” are functions

For loops can also be used for strings

Note: I omitted the curly braces at the end of the for loop, mainly because the body of the for loop only has one line of code. If there are more than one line of code, you need to use the curly braces, otherwise the result will not be what you want

The while loop

The while loop, which is also very similar to the use of while in Java, looks at the differences in syntax

Advanced for loop

If the guards

If guard mode, let’s say we want to get all the even numbers between 1 and 10, using a normal for loop, we have to loop every number out and see if it’s even. If we use the if guard in the for loop, we can perform some logic on the loop to see if it’s even

For comprehension

A typical example of a for derivation is to construct a set

When iterating numbers through a for loop, we can use yield to specify a rule that processes the iterated numbers and creates a new collection

Scala’s collection system

The top-level interface of the collection is Iterable, and there are some subinterfaces below the Iterable interface. There are specific implementation classes below the subinterfaces of Set, Seq, and Map

  • Below set are HashSet, LinkedHashSet, SortedSet, and so on
  • Seq has List, Buffer, Range and so on
  • Under Map, there is HashMap, SortedMap, LinkedHashMap, and so on
  • There are two commonly used ones below Buffer, ArrayBuffer and ListBuffer

A collection of

Collections in Scala are divided into mutable and immutable collections

  • Where a mutable set means that the elements of the set can be modified dynamically
  • An immutable set means that the elements of the set, once initialized, cannot be modified

Variable set: in scala. Collection. Mutable immutable sets below: the packet in scala. Collections. Immutable the package below we create the collection, if you do not specify a specific package name, the default will use an immutable collection

Set

So let’s take a look at a Set. A Set is a Set that has no duplicate elements. And the property of a Set is basically the same as the property of a Set in Java. Sets are mutable and immutable. By default, they’re immutable

Isn’t it strange that Set is an interface, but you can create objects, and what’s even more surprising is that you don’t need to use the new keyword, which is a bit of a twist

Note that when learning Scala, you can use Java to compare and understand more, but don’t use all the Java knowledge, because there are some differences between the two.

If you look at the Scala documentation, you’ll see that the Set is not just an interface, it’s also an Object, and we’ll look at the Object type in more detail, but you’ll need to know about it first.

Note: By default, a set created directly is an immutable set. As you can see here in the immutable package, elements in an immutable set cannot be changed once initialized, so adding elements to an immutable set will cause an error.

But notice, I’m using s plus 4 and it works

Does that contradict what we just said? No, because s plus 4 is going to return a new set, it’s going to create a new set on top of the previous set, and the new set contains the elements of the previous set and the element 4 that we added which you need to be able to distinguish if you want to create a mutable set, You can explicitly specify the package name by using the set collection under mutable

The common subclasses of Set are HashSet, LinkedHashSet, and SortedSet

  • HashSet: The unique feature of this collection is that the elements in the collection are not repeatedly unordered
  • LinkedHashSet: The feature of this set is that the elements in the set are not repeated and ordered. It will maintain the insertion order with a linked list to ensure that the elements in the set are ordered
  • SortedSet: The characteristic of this set is that the elements in the set are not repeated and ordered. It will automatically sort by the elements
scala> val s = new scala.collection.mutable.HashSet[Int]()
s: scala.collection.mutable.HashSet[Int] = Set()
scala> s +=1
res35: s.type = Set(1)
Copy the code

List

Next, take a look at List. List belongs to the subinterface of the Seq interface. List represents an immutable List

There are head, tail, and :: operations for a List

First demonstrate the head and tail operations

  • Head: gets the first element in the List
  • Tail: Gets all the elements after the first element in the List

The :: operator allows you to combine the results of head and tail into a list

:: The operator must be clear. It is reflected in the Spark source code and must be understood

In this case, List is an immutable List, which is very inconvenient to use in the real world, because we have a lot of situations where we have to dynamically add elements to lists, right?

Scala also provides a ListBuffer. ListBuffer allows you to dynamically add or remove elements

Map

Create an immutable Map

scala> val ages = Map("jack"->30."tom"->25."jessic"->23)
ages: scala.collection.immutable.Map[String.Int] = Map(jack -> 30, tom -> 25,
scala>
ages("jack") 
res100: Int = 30
Copy the code

Create a mutable Map

scala> val ages = scala.collection.mutable.Map("jack"->30."tom"->25."jessic"- ages: scala.collection.mutable.Map[String.Int] = Map(jessic -> 23, jack -> 30
scala> ages("jack") 
res101: Int = 30
Copy the code

There is also an easy way to create a Map that is immutable

scala> val ages = Map(("jack".30), ("tom".25), ("jessic"->23))
ages: scala.collection.immutable.Map[String.Int] = Map(jack -> 30, tom -> 25And...Copy the code
  • Query operation

Gets the value corresponding to the specified key. If the key does not exist, an error is reported

scala> val ages = scala.collection.mutable.Map(("jack".30), ("tom".25), ("jessic".23)) 
scala> val age = ages("jack") 
age: Int = 30
scala> val age = ages("jack1") 
java.util.NoSuchElementException: key not found: jack1
Copy the code

Therefore, it is not good to obtain directly in the actual work. If you encounter a nonexistent key program, it will report an error, resulting in the abnormal exit of the program. We can use the contains function to check whether the key exists. We can use the if-else statement to return a default value if the key does not exist

scala> val age = if (ages.contains("jack1")) ages("jack1") else 0 
age: Int = 0
Copy the code

This is no problem, is a little trouble to write up, there is no convenient usage? The map also has a getOrElse function

scala> val age = ages.getOrElse("jack1".0) 
age: Int = 0
Copy the code

It is recommended that you use this getOrElse function to retrieve data from the Map in the future

  • Modify the

Update the elements in the map

scala> ages("jack") = 31
Copy the code

Adding more than one element

scala> ages += ("hehe" -> 35."haha" -> 40)
Copy the code

Remove elements

scala> ages -= "hehe"
Copy the code
  • traverse

Traverse the entrySet of the map

scala> for ((key, value) <- ages) println(key + "" + value) 
jessic 23
jack 31
tom 25
haha 40
Copy the code

Traverse the key of the map

scala> for (key <- ages.keySet) println(key) jessic
jack
tom
haha
Copy the code

Traverse the value of the map

scala> for (value <- ages.values) println(value)
 23
 31
 25
 40
Copy the code

Finally, take a look at the subclasses of Map: HashMap, SortedMap, and LinkedHashMap

  • HashMap: A map stored in order of hash values of keys
  • SortedMap: Automatically sort keys in a Map
  • LinkedHashMap: Remember the order in which key-values are inserted

Array

You can also create arrays directly using Array(), with the element types automatically inferred

scala> val a = Array("hello"."world")
scala> a(0)
res68: String = hello
scala> val a1 = Array("hello".30) 
a1: Array[Any] = Array(hello, 30)
Copy the code

If you want to use a variable size array, you need to use an ArrayBuffer

ArrayBuffer

ArrayBuffer in Scala is similar to ArrayList in Java. ArrayBuffer is of variable length: Add and remove elements. If you don’t want to use fully qualified names every time, you can pre-import the ArrayBuffer class

scala> import scala.collection.mutable.ArrayBuffer   
import scala.collection.mutable.ArrayBuffer
Copy the code
  • Initialize the

Note: it is also possible to create and initialize an empty ArrayBuffer directly (1,2,3,4)

scala> val b = new ArrayBuffer[Int]()  
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(a)Copy the code
  • Add elements

Using the += operator, you can add one or more elements b += 1 or b += (2, 3, 4, 5).

scala> b += 1
res69: b.type = ArrayBuffer(1)
scala> b += (2.3.4.5)  
res70: b.type = ArrayBuffer(1.2.3.4.5)
Copy the code

You can insert an element at the specified position using the insert() function, but this operation is inefficient because you need to move all the elements after the specified position to add an element 30 to the position of 3 icon

scala> b.insert(3.30)
Copy the code
  • Remove elements

Use the remove() function to remove the element at the specified location

b.remove(0)
Copy the code

Note: Arrays and ArrayBuffers can be converted to each other

B. Toarray: converting ArrayBuffer toArray. A. Tobuffer: converting Array to ArrayBuffer

Tuple

Tuple: A Tuple is called a Tuple. It is immutable like an Array, but unlike an Array, a Tuple can contain different types of elements. The corner of a Tuple starts at 1

Note: Scala currently supports tuples of a maximum length of 22, with collections or arrays available for larger sizes

scala> val t = (1.3.14."hehe")
t: (Int.Double.String) = (1.3.14,hehe)
scala> t._1 
res117: Int = 1
scala> t._3
res118: String = hehe
Copy the code

A complete written

Where Tuple3, 3 is the number of elements

conclusion

We’ve talked about a lot of data structures in the set system, some are mutable, some are immutable, some are both mutable and immutable, it sounds a little confusing, here we summarize the variable set: LinkedHashSet, ListBuffer, ArrayBuffer, LinkedHashMap immutable set: Set, HashSet, SortedSet, Map, HashMap and two extras: Array and Tuple

Array: Its length is immutable and its elements are variable

Tuple: The length is immutable, and the elements inside are immutable

Use of functions in Scala

Definition of a function

To define a function in Scala, you need to use the def keyword. A function includes the name, parameters, and body of the function. Scala requires that you give the types of all the parameters of the function, but the type of the return value of the function is not required because Scala can infer the type of the return value from the expressions in the body of the function. The return value of the last line of code in the function is the return value of the entire function. There is no need to use return, unlike in Java, where the return value of a function must be used below return to implement a single-line or multi-line function

  • A single function
scala> def sayHello(name: String) = print("Hello, " + name) 
sayHello: (name: String)Unit
scala> sayHello("Scala") Hello.Scala
Copy the code
  • Multi-line function
scala> :paste
// Entering paste mode (ctrl-D to finish)
def sayHello(name: String, age: Int) = { println("My name is "+name+",age is "+age)
age }
// Exiting paste mode, now interpreting. sayHello: (name: String, age: Int)Int
scala> sayHello("Scala".18) 
My name is Scala,age is 18 res120: Int = 18
Copy the code

Object-oriented programming in Scala

Here we’ll focus on classes, objects, and interfaces in Scala

Note: Classes in Scala and classes in Java are basically the same as objects in Scala that need to be defined, whereas objects in Java are derived from class new. Interfaces in Scala are traits, and interfaces in Java are interfaces

Class – the class

So let’s first take a look at the class definition in Scala just like in Java, you define classes using the class keyword and you create objects using the new keyword just like in Java. So let’s take a look at a specific example

class Person{
var name = "scala"
  def sayHello(){
    println("hello," +name)
  }
  def getName= name
}
Copy the code

Note: if () is specified when a method is defined, then () can be called with or without (). If () is not specified when a method is defined, then () cannot be called with ()