preface

Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now

Where t

Computing Engines Now that we’re done with Mr, let’s move on to Spark

Scala profile

Scala, short for Scalable Language, is a multi-paradigm programming Language. Martin Odersky at the Federal Institute of Technology in Lausanne (EPFL) began designing Scala based on the work of Funnel in 2001. Funnel is a programming language that combines functional programming with Petri nets. Odersky’s previous work was on Generic Java and JavAC (The Sun Java compiler). Scala for the Java platform was released in late 2003 / early 2004. Scala for the.NET platform was released in June 2004. The second version of the language, V2.0, was released in March 2006. As of September 2009, the latest release is version 2.7.6. Scala 2.8 is expected to include a rewritten Scala Collections library, named and default parameters for methods, package objects, and continuations. In April 2009, Twitter announced that they had migrated most of their back-end applications from Ruby to Scala, with the rest planning to migrate as well. In addition, Wattzon has publicly stated that its entire platform is already written based on the Scala infrastructure.

Scala feature

Object-oriented features

Scala is a pure object-oriented language where every value is an object. The data types and behavior of objects are described by classes and attributes. There are two ways to extend class abstraction: one is subclass inheritance, the other is a flexible mixin mechanism. These two approaches avoid the problems of multiple inheritance.

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. Further, programmers can take advantage of Scala’s pattern matching to write regular expression-like code to process XML 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.

scalability

Scala’s design is rooted in the fact that, in practice, domain-specific application development often requires domain-specific language extensions. Scala offers a number of unique language mechanisms that make it easy and seamless to add new language constructs in the form of libraries:

  • Any method can be used as a prefix or postfix operator
  • Closures can be constructed automatically based on the expected type.

Scala data types

Scala has the same data types as Java. The following table lists the data types supported by Scala:

Scala variable

A variable is a convenient placeholder used to refer to a computer memory address. The variable takes up some memory space after it is created. Based on the variable’s data type, the operating system allocates memory and decides what will be stored in reserved memory. So, by assigning variables to different data types, you can store integers, decimals, or letters in these variables

In Scala, variables are declared using the keyword “var” and constants are declared using the keyword “val”. In fact, comparing Java is to add final or not

Scala access modifiers

Scala access modifiers are basically the same as Java access modifiers: private, protected, public. If no access modifier is specified, Scala objects are public by default. The private qualifier in Scala is stricter than in Java; in the case of nested classes, the outer class cannot even access the private members of the nested class.

Scala operator.

An operator is a symbol that tells the compiler to perform a specified mathematical and logical operation.

Scala has a wealth of built-in operators including the following types:

  • Arithmetic operator
  • Relational operator
  • Logical operator
  • An operator
  • The assignment operator

Basically consistent with Java, here I will not give an example

IF and circulation

object Test { def main(args: Array[String]) { var x = 10; if( x < 20 ){ println("x < 20"); }}}Copy the code
object Test { def main(args: Array[String]) { var a = 10; // infinite loop while(true){println("a = "+ a); }}}Copy the code

It’s the same with Java

Scala methods and functions (very different from Java)

Scala has methods and functions, and the semantic differences between the two are minimal. Scala methods are part of a class, while functions are objects that can be assigned to a variable. In other words, functions defined in a class are methods.

  • Methods in Scala are similar to Java in that methods are part of a class.
  • A function in Scala is a complete object, and a function in Scala is an object that inherits a Trait class.
  • Scala uses the val statement to define functions and the DEF statement to define methods.
class Test{
  def m(x: Int) = x + 3
  val f = (x: Int) => x + 3
}
Copy the code

Method statement

Def functionName ([parameter list]) : [return type]

Method definition

The method definition starts with a def keyword, followed by a list of optional arguments, a colon: and the method return type, an equals sign =, and finally the body of the method. The Scala method definition format is as follows:

Def functionName ([expr]) : [return type] = {function body return [expr]}Copy the code

The return type in the above code can be any valid Scala data type. Arguments in the argument list can be separated by commas.

object add{
   def addInt( a:Int, b:Int ) : Int = {
      var sum:Int = 0
      sum = a + b
      return sum
   }
}
Copy the code

The method call

Scala provides many different methods for calling a method: Here is the standard format for calling a method:

FunctionName (Parameter list)

If the method is called using an instance object, we can use a Java-like format (using. ) :

[instance.]functionName(Parameter list)

Object Test {def main(args: Array[String]) {println("Returned Value: "+ addInt(5,7)); } def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum } }Copy the code

Scala closure

A closure is a function whose return value depends on one or more variables declared outside the function. Closures can generally be thought of simply as another function that accesses local variables within a function. Here’s an anonymous function:

val multiplier = (i:Int) => i * 10  
Copy the code

There is a variable I inside the function, which is an argument to the function. Here’s another code:

val multiplier = (i:Int) => i * factor
Copy the code

In the multiplier there are two variables: I and factor. One of the I’s is a formal parameter to the function, which is assigned a new value when the Multiplier function is called. However, factor is not a formal parameter, but a free variable. Consider the following code:

var factor = 3  
val multiplier = (i:Int) => i * factor  
Copy the code

Here we introduce a free variable factor, which is defined outside the function.

The function variable multiplier thus defined becomes a “closure” because it refers to variables defined outside the function. The process of defining the function is to capture the free variable to form a closed function.

object Test { def main(args: Array[String]) { println( "muliplier(1) value = " + multiplier(1) ) println( "muliplier(2) value = " + multiplier(2) ) }  var factor = 3 val multiplier = (i:Int) => i * factor }Copy the code

Scala string

The following example assigns a string to a constant:

object Test {
   val greeting: String = "Hello,World!"

   def main(args: Array[String]) {
      println( greeting )
   }
}
Copy the code

The above example defines the variable greeting, which is a String constant of type String (java.lang.string). In Scala, the String type is actually Java String, which has no String class of its own. In Scala, String is an immutable object, so it cannot be modified. This means that if you modify a string it will create a new string object. But other objects, like arrays, are mutable objects. Next we’ll introduce you to the common java.lang.String methods.

We mentioned earlier that strings are immutable. If you need to create a String that can be modified, you can use the String Builder class as follows:

object Test { def main(args: Array[String]) { val buf = new StringBuilder; buf += 'a' buf ++= "bcdef" println( "buf is : " + buf.toString ); }}Copy the code

The specific String method, we go to see, here is not a list

Scala arrays

Arrays are provided in Scala to store fixed-size elements of the same type, and arrays are an important data structure for every editing language. Declaring array variables is not declaring number0, number1,… Instead, declare a variable like numbers and use numbers[0], numbers[1]… And numbers[99] to represent individual variables. A specified element in an array is accessed by index. The first element of the array has an index of 0, and the last element has an index of the total number of elements minus 1.

Declare an array

Here is the syntax for Scala array declarations:

Var z:Array[String] = new Array[String](3)Copy the code

It’s almost like Java

Scala Collection

Scala provides a good set of collections implementations that provide some abstraction of collection types. Scala collections are divided into mutable and immutable collections. Mutable collections can be updated or extended where appropriate. This means you can modify, add, and remove elements from a collection. Immutable collection classes, by contrast, never change. However, you can still simulate add, remove, or update operations. But these operations will return a new collection in each case, leaving the original collection unchanged. Next, we’ll introduce some applications of common collection types:

Scala classes and objects

A class is an abstraction of an object, and an object is a concrete instance of a class. Classes are abstract and take up no memory, while objects are concrete and take up storage. A class is a blueprint for creating an object. It is a software template that defines methods and variables to be included in a particular type of object.

We can use the new keyword to create an object of class as shown in the following example:

class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: {x = x + dx y = y + dy println ("x: "+ x); Println ("y: "+ y); }}Copy the code

Classes in Scala are not declared public, and there can be multiple classes in a Single Scala source file. The above example class defines two variables x and y, and a method: move, which returns no value. Scala class definitions can have parameters, called class parameters, as shown above in xc and yc, and class parameters are accessible throughout the class. We can then use new to instantiate the class and access methods and variables in the class:

import java.io._ class Point(xc: Int, yc: Int) { var x: Int = xc var y: Int = yc def move(dx: Int, dy: {x = x + dx y = y + dy println ("x: "+ x); Println ("y: "+ y); } } object Test { def main(args: Array[String]) { val pt = new Point(10, 20); // Move to a new position pt. Move (10, 10); }}Copy the code

The Scala Trait

The Scala Trait is Java’s equivalent of an interface, and in fact more powerful than that. Unlike interfaces, it can also define implementations of properties and methods. Normally Scala classes can only inherit from a single parent, but traits can inherit from multiple classes, resulting in multiple inheritance. A Trait is defined in a similar way to a class, but it uses the keyword Trait, as follows:

trait Equal { def isEqual(x: Any): Boolean def isNotEqual(x: Any): Boolean = ! isEqual(x) }Copy the code

The traits above are made up of two methods: isEqual and isNotEqual. The isEqual method does not define the implementation of the method; isNotEqual does. Subclass inheritance features can implement unimplemented methods. So the Scala traits are actually more like Abstract Java classes.

A complete example of the feature is shown below:

Def isNotEqual(x: Any): Boolean =! Def isNotEqual(x: Any): Boolean =! isEqual(x) } class Point(xc: Int, yc: Int) extends Equal { var x: Int = xc var y: Int = yc def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x } object Test { def main(args: Array[String]) { val p1 = new Point(2, 3) val p2 = new Point(2, 4) val p3 = new Point(3, 3) println(p1.isNotEqual(p2)) println(p1.isNotEqual(p3)) println(p1.isNotEqual(2)) } }Copy the code

Scala Pattern matching

Scala provides a powerful pattern matching mechanism and is widely used. A pattern match consists of a series of alternatives, each beginning with the keyword case. Each alternative contains a pattern and one to more expressions. The arrow symbol => separates patterns from expressions.

Here is a simple pattern matching example of an integer value:

object Test {
   def main(args: Array[String]) {
      println(matchTest(3))

   }
   def matchTest(x: Int): String = x match {
      case 1 => "one"
      case 2 => "two"
      case _ => "many"
   }
}
Copy the code
 scalac Test.scala 
$ scala Test
many
Copy the code

Scala regular expressions

Scala supports regular expressions through the Regex class in the Scala.util. matching package. The following example demonstrates using regular expressions to find the word Scala:

import scala.util.matching.Regex

object Test {
   def main(args: Array[String]) {
      val pattern = "Scala".r
      val str = "Scala is Scalable and cool"
     
      println(pattern findFirstIn str)
   }
}
Copy the code

Scala Exception Handling

Scala’s exception handling is similar to other languages such as Java. Scala’s methods can terminate code by throwing an exception instead of returning a value.

Scala throws exceptions the same way Java does, using the throw method, for example, to throw a new parameter exception:

throw new IllegalArgumentException

The mechanism for catching exceptions is the same as in other languages. If an exception occurs, the catch words are caught in order. Thus, in catch sentences, the more specific exceptions are brought forward and the more general exceptions are brought back. If the exception thrown is not in the catch clause, it cannot be handled and is upgraded to the caller.

The catch clause, which catches exceptions, has a different syntax than in other languages. In Scala, the idea of pattern matching is borrowed for exception matching, so in catch code, there are a series of case words, as shown in the following example

import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException

object Test {
   def main(args: Array[String]) {
      try {
         val f = new FileReader("input.txt")
      } catch {
         case ex: FileNotFoundException =>{
            println("Missing file exception")
         }
         case ex: IOException => {
            println("IO Exception")
         }
      }
   }
}
Copy the code

“Catch” is the same as “case” in “match”. Since exception catching is sequential, if the most common exception, Throwable, is written first, no case after it will be caught, so it needs to be written last.

The finally statement is used to execute a step that needs to be executed either normally or when an exception occurs. An example of the finally statement is as follows:

import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Test { def main(args: Array[String]) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException => { println("Missing file exception") } case ex: IOException => { println("IO Exception") } } finally { println("Exiting finally..." )}}}Copy the code

Scala Extractor

The extractor extracts the parameters that construct the object from the object passed to it. The Scala standard library contains some predefined extractors, which we’ll look at briefly. The Scala extractor is an object with unapply methods. The unapply method is the reverse of the Apply method: Unapply takes an object and extracts the values from the object, usually the values used to construct that object.

The following example demonstrates the mail address extractor object:

Object Test {def main(args: Array[String]) {println ("Apply method: "+ Apply ("Zara", "gmail.com")); Println ("Unapply method: "+ Unapply ("[email protected]")); Println ("Unapply: "+ Unapply ("Zara Ali")); If (user: String, domain: String) = {user +"@"+ domain} if (user: String, domain: String) = {user +"@"+ domain} Option[(String, String)] = { val parts = str split "@" if (parts.length == 2){ Some(parts(0), parts(1)) }else{ None } } }Copy the code

At the end

Introduction to Scala, recently written are few people read, but still have to follow their own learning process to write it, come on! SAO Year!!

Daily for praise

Ok, everybody, that’s all for this article, you can see people here, they are real fans.

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article

Wechat search “six pulse Excalibur program life” reply 888 I find a lot of information to you