Scala Quick Start -1- Declare variables

background

  • Because Spark is developed in Scala, you need to learn the Scala language before developing Spark applications. Spark also supports Java and Python, but as a Java programmer, I decided to learn Scala.
  • Scala is a language that runs on the JVM. The development is very efficient, the syntax is rich and concise, and a couple of lines of Scala code can take care of a lot of code in Java.
  • Scala’s syntax is too sweet

Scala feature

Object-oriented features

  • Scala is a pure object-oriented language where every value is an object.

Functional programming

  • Scala is also a functional language, and functions can also be used as values. Scala provides a lightweight syntax for defining anonymous functions, supports higher-order functions, allows nesting of multiple layers of functions, and supports currization. Scala’s Case class and its built-in pattern matching are equivalent to the algebraic types commonly used in functional programming languages.
  • You can use Scala’s pattern matching to write regular expression-like code to process data.

concurrency

  • Scala uses actors, thread-like entities that receive messages through “mailboxes,” as its concurrency model. Actors can reuse threads, so millions of actors can be used in a program, while threads can only create thousands. In versions after 2.10, Akka is used as its default Actor implementation.

The main content

  • Declare variables and common types
  • Control structures (conditions, loops, for), functions
  • Common array operations
  • Classes and objects
  • Inheritance and traits
  • A collection of
  • Pattern matching and sample classes

Declare variables and common types

  • The Scala code is compiled into bytecode and handed to the Java Virtual machine for execution.
  • It is not mandatory to specify the type of the variable; the compiler will infer it.
scala> 8 * 5
res0: Int = 40
Copy the code
  • The value defined by val cannot change its contents. In Scala, the use of val is encouraged.
scala> val answer = 8 * 5
answer: Int = 40

scala> answer = 10
<console>:8: error: reassignment to val
       answer = 10
Copy the code
  • If you want to declare a variable whose value is variable, use var.
scala> var counter = 0
counter: Int = 0

scala> counter = 10
counter: Int = 10
Copy the code
  • The type of a variable or function is always written after the variable or function name, contrary to Java convention.
scala> val greeting : String = "Hello"
greeting: String = Hello
Copy the code
  • Don’t use semicolons Finally, semicolons are needed only when there are multiple statements in the same line of code.
  • The common data types are the same as in Java: Byte, Char, Short, Int, Long, Float, Double, and Boolean, which are all classes.
  • Converting between primitive and wrapper types is the job of the Scala compiler.
  • Operators such as +-*/% are actually methods.
  • For BigInt and BigDecimal objects, you can use the mathematical operator in the usual way (but in Java the same operation is written as x.multiply(x)).
scala> val x : BigInt = 123
x: BigInt = 123

scala> x * x
res1: scala.math.BigInt = 15129
Copy the code
  • Scala methods that take no arguments generally do not use parentheses, and methods that take no arguments and do not change the current object do not use parentheses.

Scala Quick Start -2- Control structures and functions

background

  • Expressions have values and statements perform actions.
  • In Scala, almost all constructed syntactical structures have values, unlike In Java, where expressions and statements (if statements) are divided into two categories.
  • Here the if representation has a value.
  • Code blocks also have values, and the last expression is the value.
  • Statement, semicolons are not required.
  • Return is not used in functions.

conditionsexpression

  • In Scala, if/else expressions have a value, which is the value of the expression after if or else.
scala> var x = 10
x: Int = 10

scala> val r = if (x > 0) 1 else -1
r: Int = 1

scala> var x = 0
x: Int = 0

scala> val r = if (x > 0) 1 else -1
r: Int = -1
Copy the code
  • Maybe if has no output value, but in Scala, every expression has some kind of value.
scala> var x = 0
x: Int = 0

scala> val r = if (x > 0) 1
r: AnyVal = ()
Copy the code

Block expressions and assignments

  • In Scala, the {} block contains a series of expressions, and the result is an expression. The value of the last expression in the block is the value of the block.
  • This is useful for cases where the initialization of a val needs to be done in multiple steps.
val dis = {val dx = x - x0; val dy = y - y0; sqrt(dx * dx + dy * dy)}
Copy the code

cycle

  • While is like a loop in Java.
while(n > 0) {
	r = r * n
	n -= 1
}
Copy the code
  • Scala has no for(initialization; Check whether variables are met; Update variable) structure.
for(i <- 1 to n) {
	r = r * i
}
Copy the code
  • The 1 to n expression returns the range from 1 to n (inclusive).
  • 1 until n The expression returns data between 1 and n (excluding data).

Enhance for loops and for comprehensions

  • Multiple generators can be provided in the form of a variable <- expression, separated by a semicolon
scala> for(i <- 1 to 3; j <- 1 to 3) print ((10 * i + j) + " ")
11 12 13 21 22 23 31 32 33
Copy the code
  • Each generator can take a guard, a Boolean expression beginning with if (if is not preceded by a semicolon)
scala> for(i <- 1 to 3; j <- 1 to 3 if i ! = j) print((10 * i + j) + " ") 12 13 21 23 31 32Copy the code
  • For derivation: a for loop whose loop begins with yield constructs a set, each iteration producing one value from the set
scala> for(i <- 1 to 10) yield i % 3
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 0, 1, 2, 0, 1, 2, 0, 1)
Copy the code

function

  • Function definition: Specify the function name, parameters, and function body in the following format
def abs(x: Double) = if (x >= 0) x else -x
Copy the code
  • The types of all parameters must be given
  • Recursive functions must specify a return value type
def fac(n: Int) : Int = if(n <= 0) 1 else n * fac(n - 1)
Copy the code
  • Don’t needreturnstatements
  • There are=The equal sign joins the body of the function
  • Default and named parameters
scala> def decorate(str: String, left: String = "[", right: String = "]") = left + str + right
decorate: (str: String, left: String, right: String)String

scala> decorate("Hello World")
res3: String = [Hello World]

scala> decorate("Hello World", "<", ">")
res4: String = <Hello World>
Copy the code
  • You can also specify parameter names when you supply parameter values, so that they are not in the order in which the function defines the parameter list
scala> decorate(left = "<<", str = "Hello Scala", right = ">>")
res5: String = <<Hello Scala>>
Copy the code
  • You can mix unnamed and named parameters, as long as the unnamed parameter comes first
scala> decorate("Hello Spark", right = "]<<") res6: String = [Hello Spark]<< equivalent to Scala > decorate("Hello Spark", "[", "]<<")Copy the code
  • Implement a function that can accept a variable-length argument list
scala> def sum(args: Int*) = {
     | var result = 0
     | for (arg <- args) result += arg
     | result
     | }
sum: (args: Int*)Int

scala> val s = sum(1, 3, 5, 7)
s: Int = 16
Copy the code
  • You can use_ *Converts an integer range to a sequence of parameters
Scala > val ss = sum(1 to 5) <console>:8: error: type mismatch; found : scala.collection.immutable.Range.Inclusive required: Int val ss = sum(1 to 5) scala> val ss = sum(1 to 5: _*) ss: Int = 15Copy the code
  • If the function body is enclosed in curly braces, but does not precede=The return type is Unit. Such a function is called a procedure. The procedure does not return a value and is called only for its side effects.
  • When val is declared lazy, its initiation is delayed until it is first evaluated.
Lazy val words = scala.io.source.fromfile ("/usr/share/dict/words").mkstring See if an error is reported when the initialization statement is executed (file not found only when words are accessed)Copy the code

Scala Quick Start -3- Common array operations

knowledge

  • Use Array for fixed length, and ArrayBuffer for variable length
  • Do not use new when providing initial values
  • Use () to access elements
  • For (elem < -arr) traverses the elements
  • For (elem < -arr if…) Yield… Convert the original array to the new array

Fixed-length array

  • An array of 10 integers, all of which start with 0
scala> val nums = new Array[Int](10)
nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
Copy the code
  • Array of 10 elements in characters, all elements initialized to NULL
scala> val str = new Array[String](10)
str: Array[String] = Array(null, null, null, null, null, null, null, null, null, null)
Copy the code
  • Providing an initial value does not require new, Array[String] of length 2, the type is inferred
scala> val str1 = Array("Hello", "Scala")
str1: Array[String] = Array(Hello, Scala)
Copy the code
  • Use () to access elements
scala> val s = str1(0)
s: String = Hello
Copy the code

Variable-length array

  • ArrayBuffer, a data structure equivalent to ArrayList in Java
  • Initialize an empty variable-length array, ready to store integers
scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val b = ArrayBuffer[Int]()
b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()
Copy the code
  • Add elements to the end with += or multiple elements wrapped in parentheses
scala> b += 1
res0: b.type = ArrayBuffer(1)

scala> b += (1, 2, 3)
res1: b.type = ArrayBuffer(1, 1, 2, 3)
Copy the code
  • Append any collection with the ++= operator
scala> b ++= Array(6, 8, 9)
res2: b.type = ArrayBuffer(1, 1, 2, 3, 6, 8, 9)
Copy the code
  • Remove the last two elements
scala> b.trimEnd(2)

scala> b
res4: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 1, 2, 3, 6)
Copy the code
  • Elements can be inserted or removed at any position (inefficient, all elements after that position must be shifted)
// Insert scala> b.insert(2, 4) scala> b res6 before subscript 2: Scala. Collection. Mutable. ArrayBuffer [Int] = ArrayBuffer (1, 1, 4, 2, 3, 6) / / before the subscript 2 insert multiple elements scala > b.i nsert (2, 4, 5) scala> b res8: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 1, 4, 5, 4, 2, 3, 6)Copy the code
  • Fixed – length array and variable – length data conversion
Scala > b.toarray res9: Array[Int] = Array(1, 1, 4, 5, 4, 2, 3, 6) scala> B.tobuffer res10: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 1, 4, 5, 4, 2, 3, 6)Copy the code

Through the array

Subscripting access scala / / > for (I < 0 until b.l ength) | println (I + ":" + b) (I) 1-0 1:1 2:4 3:5 Deborah 5-2 6:3 but / / don't use subscript scala > for(elem <- b) | println(elem) 1 1 4 5 4 2 3 6Copy the code

An array of conversion

  • The for derivation transforms an array to generate a new array
scala> val a = Array(2, 3, 5, 7)
a: Array[Int] = Array(2, 3, 5, 7)

scala> val res = for(elem <- a) yield 2 * elem
res: Array[Int] = Array(4, 6, 10, 14)

scala> a
res13: Array[Int] = Array(2, 3, 5, 7)
Copy the code
  • To convert from an ArrayBuffer to a new ArrayBuffer
scala> a.toBuffer
res14: scala.collection.mutable.Buffer[Int] = ArrayBuffer(2, 3, 5, 7)

scala> val res = for(elem <- res14) yield 2 * elem
res: scala.collection.mutable.Buffer[Int] = ArrayBuffer(4, 6, 10, 14)
Copy the code

Author: Yezhiwei

Links:

  • Scala quickstart – 1 – declaring variables | | Yezhiwei Blog Yezhiwei Blog
  • Scala quickstart – 2 – control structure | | Yezhiwei Blog Yezhiwei Blog
  • Scala quickstart – 3 – common array operations | | Yezhiwei Blog Yezhiwei Blog

Statement: This article comes from the network, copyright belongs to the author, please indicate reprint, if there is any problem, please contact us, thank you!