In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
[TOC]
Introduction to Scala
Scala is a multi-paradigm programming language, which is designed to integrate the features of object-oriented programming and functional programming.
Scala runs on the Java virtual machine and is compatible with existing Java programs.
The Scala source code is compiled into Java bytecode, so it can run on JVM and can call existing Java class libraries.
Functional programming paradigm is more suitable for Map/Reduce and big data model, it abandons the calculation model of data and state, and focuses on the function itself, rather than the data and state processing of the executing process. The logic of function paradigm is clear and simple, and it is very suitable for dealing with batch processing based on immutable data, which are basically transformed by map and reduce operations to generate new copies of data, and then processed.
People like Spark,Flink are developed with Scala, so it is necessary to learn from big data and master scala.
Official website: http://scala-lang.org/
Scala installation verification 1, install JDK2, JAVA_HOME, PATH3, Maven4, SCALA SDK download address: http://scala-lang.org/download/all.html the selected version here is Scala 2.10.5 Divided into windows and linux version 5, configure SCALA_HOME to add SCALA_HOME6 to windows environment variables, verify scala-versionScala code runner version 2.10.5-- Copyright 2002-2013, LAMP/EPFL starter object HelloWorld {def main (args: array [string]): Unit = {println ("HelloWorld!")}}
Save as HelloWorld.scala, and then perform the following two steps:
Scalac HelloWorld.scalascala HelloWorldScala basic knowledge and grammar language features 1. Expandable object-oriented functional programming 2. Compatible with JAVA class library call interoperability 3. Syntax concise code line short type inference abstract control 4. Static typing verifies security refactoring 5. Support concurrency control strong computing power to customize the relationship between other control structures Scala and Java
1. All run on the JVM virtual machine.
The files compiled by Scala are also .class, which are converted to bytecode and then run on the JVM virtual machine.
2. Scala and Java call each other
The code of Java can be called directly in Scala, and the code of Scala can also be called directly in Java.
3 、 Java8 VS Scala
1) before Java8 (lambda) came out, Java was just an object-oriented language, but after Java8 came out, Java was a mixed language of object-oriented and function-oriented.
2) first of all, we need to accurately locate Scala, to some extent, Scala is not a pure function-oriented programming language, some people think that Scala is a static object-oriented language with closures), more accurately, Scala is a mixture of function-oriented and object-oriented.
3) Scala was originally designed for function-oriented FP, while Java started as object-oriented OO. Now both of them are mixed languages of OO and FP. Can you think of it this way: Scala= FP + OO, and Java = OO + FP?
Because the two normal forms of object-oriented OO and function-oriented FP are similar to Abscissa and ordinate in different coordinate directions, and similar to the mismatched impedance relationship between database and object, if they are not combined well, they may not produce the effect of 1: 1 > 2.
Object-oriented is the closest way to human thinking, while function-oriented is the closest to computer thinking. If you want the computer to model the human business, then focus on OO; if you want the computer to automatically model from big data through algorithms, then focus on FP. Therefore, Java may also occupy the main market in enterprise engineering software, while Scala will seize the Java market in scientific computing, big data analysis and other fields. For example, Scala's Spark has a tendency to replace Java's Hadoop.
Scala interpreter and IDEA
1. The Scala interpreter reads an expression, evaluates it, prints it, and then goes on to read the next expression. This process is called a read-evaluate-print-loop, or REPL.
Technically, the scala program is not an interpreter. What actually happens is that what you type is quickly compiled into bytecode, which is then handed over to the Java virtual machine for execution. Because of this, most scala programmers prefer to call it "REPL"
2 、 scala
Scala > "Hello" res1: String = Helloscala > 1+2res5: Int = 3scala > "Hello" .filter (line= > (linework examples)) res2: String = Heo
You should notice that after we enter each statement of the interpreter, it outputs a line of information, similar to res0:
Java.lang.String
= Hello. The first part of the output is the variable name given to the expression by REPL. In these examples, REPL defines a new variable (res0 to res3) for each expression. The second part of the output (the following part) is the static type of the expression. The first example is of type java.lang.String, and the last example is of type scala.util.matching.Regex. The last part of the output is the stringed display of the result after the expression is evaluated. The output is usually obtained by calling the toString method on the result, and JVM defines the toString method for all classes.
Var and val define variables
1. There is no static class in Scala, but it has a similar companion object.
2. Fields:
Field / variable definition Scala uses var/val variable / invariant name: type to define, for example:
Var index1: Int = 1 val index2: Int = 1
The difference between var and val is that var is a variable, and later values can be changed. The value of val can only be assigned when it is declared, but val is not a constant, it can only be said to be an invariant or read-only variable.
3. You will certainly think that the declaration of this var/val name: type is too tedious, there is another way
So when you declare a field, you can use the compiler to automatically infer the type, that is, you don't have to write: type, for example:
Var index1 = 1 (type inference) val index2 = 1
This example demonstrates a capability called type inference (type inference), which allows scala to automatically understand the types you have omitted. Here, you initialize index1 with the literal quantity int, so scala infers that the type of index2 is Int. In cases where types can be inferred automatically by the Scala interpreter (or compiler), it is not necessary to write type annotations.
4 、 a. Method (b)
The method here is a method with two parameters (one displayed and one implicit).
1.to (10), 1 to 10, 1 until 10scala > 1.to (10) res19: scala.collection.immutable.Range.Inclusive = Range (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala > 1 to 10res20: scala.collection.immutable.Range.Inclusive = Range (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala > 1 until 10res21: scala.collection.immutable.Range = Range (1,2,3,4,5,6,7,8,9)
5. In fact, according to the idea of functional programming, the var variable is a bad existence. In Scala, it is recommended that we use the invariant of val as much as possible, mainly because
1) the immutability of val helps to sort things out, but relatively comes at a cost of performance. 2) another point is that if you use var, you may worry that the value will be changed incorrectly. 3) the second advantage of using val instead of var is that it can better support equivalent inference data types and operators
scala has the same data types as java, and the memory layout and precision of java data types are exactly the same.
The following table shows the data types supported by scala:
The data types listed in the above table are all objects, which means that scala does not have native types in java. In other words, scala has no concept of basic data types and wrapper types.
In Scala, you can discard the empty parentheses for method calls. The exception is to add parentheses if the method has side effects, such as println (), but remove the parentheses if the method has no side effects, such as toLowerCase called on String:
Scala > "Hello" .toLowerCaseres22: String = helloscala > "Hello" .toLowerCase () res23: String = hello Mathematical Operation
In Scala, you can discard the empty parentheses for method calls. The exception is to add parentheses if the method has side effects, such as println (), but remove the parentheses if the method has no side effects, such as toLowerCase called on String:
You can invoke mathematical methods in any number type through the infix operator, plus sign (+), minus sign (-), multiplication sign (*), division sign (/) and remainder (%). The basic operation in scala is the same as java.
Scala > 1.2 + 2.3 res6: Double = 3.5 scala > 3-1 res7: Int = 2 scala >'b' -'a 'res8: Int = 1 scala > 2L * 3L res9: Long = 6 scala > 11 / 4 res10: Int = 2 scala > 11% 4 res11: Int = 3 scala > 11.0f / 4.0f res12: Float = 2.75 scala > 11.0% 4.0 res13: Double = 3.0 Relations and logical Operations
You can use relational methods: greater than (>), less than (=) and less than or equal to (1 > 2 res16: Boolean = false scala > 1)
< 2 res17: Boolean = true scala>1.03.5f > = 3.6f res19: Boolean = false scala >'a' > = 'A'res20: Boolean = true scala > val thisIsBoring =! true thisIsBoring: Boolean = false scala >! thisIsBoringres21: Boolean = true object equivalence scala > ("he" + "llo") = "hello" res33: Boolean = true = compare two different objects scala > 1 = 1.0res34: Boolean = true
It compares values, not address values in the concept of Java. The second example, 1 = = 1. 0, will be true because 1 will do a type promotion to 1. 0.
Scala control structure If expression has value
1. The if/else syntax structure of Scala is the same as Java or C++, but in Scala, the if/else expression has a value, which is the value of the expression after if or else.
Val x = 3if (x > 0) 1 else-1
The value of the above expression is 1 or-1, which depends on the value of x, and you can also copy the value of the if/else expression to the variable
Val s = if (x > 0) 1 else-1 / / this has the same effect as the following statement if (x > 0) s = 1 else s =-1
However, the first is better because it can be used to initialize a val, while in the second, s must be var
2. Val result = if (personAge > 18) "Adult" else 0
One of the branches is java.lang.string and the other type is Int, so their public superclass is Any
3. If else is lost
If (x > 0) 1
Then it is possible that the if statement has no output value, but in Scala, every expression has a value. The solution to this problem is to introduce a Unit class and write (). The if statement without else statement is equivalent to if (x > 0) 1else ().
Statement termination
1. In Java and C++, each statement ends with a semicolon. But in Scala-similar to JavaScript and other languages-the position of the end of a line does not need a semicolon. Similarly, there is no need to write semicolons in}, else, and similar locations.
However, if you want to write multiple statements on a single line, you need to separate them with semicolons
If (n > 0) {r = r * n; n Mutual 1}
We need to separate r = r * n from n-= 1 with a semicolon, and since there is}, there is no need to write a semicolon after the second statement.
2. Branch display
If (n > 0) {r = r * n n murmur 1} Fast expressions and assignments in Java or C++, a fast statement is a sequence of statements contained in}. You can use quick statements whenever you need to branch in logic or like to perform multiple actions. In Scala, {} quickly contains some column expressions, and the result is also an expression. The value of the last expression in the block is the fast value. Scala > val n = 9n: Int = 9scala > var f = 0f: Int = 0scala > var m = 5m: Int = 5scala > val d = if (n
< 18){f = f + n ; m = m + n ; f + m}d: AnyVal = 23输入和输出 如果要打印一个值,我们用print或println函数。后者在打印完内容后会追加一个换行符。举例来说, print("Answer:")println(42) 与下面的代码输出的内容相同: println("Answer:" + 42) 另外,还有一个带有C风格格式化字符串的printf函数:system.in printf("Hello,%s! You are %d years old.\n", "Fred", 42) 你可以用readLine函数从控制台读取一行输入。如果要读取数字、Boolean或者是字符,可以用readInt、readDouble、readByte、readShort、readLong、readFloat、readBoolean或者readChar。与其他方法不同,readLine带一个参数作为提示字符串: scala>Val name = readLine ("Please input your name:") Please input your name:name: String = xpleaf
A simple example of input and output is as follows:
Val name = readLine ("What's Your name:") print ("Your age:") val age = readInt () if (age > 18) {printf ("Hello,% s! Next year, your will be% d.\ n", name, age + 1)} else {printf ("Hello,% s! You are still a children your will be% d.\ n", name, age + 1 + "Come upstream!")}} cycle while
Scala has the same while and do loops as Java and C++. For example:
Object _ 04LoopDemo {def main (args: Array [String]): Unit = {var sum = 0 var I = 1 while (I < 11) {sum + = I + = 1} cycle do while
Scala also has a do-while loop, which is similar to the while loop, except that it checks whether the condition is met after the loop body is executed. For example:
Object _ 04LoopDemo {def main (args: Array [String]): Unit = {var sum = 0 var I = 1 do {sum + = I I + = 1} while (I 0) {val name = readLine ("pro Please enter the user name: ") val pwd = readLine (" Please enter the password: ") if (name = = dbUser & & pwd = = dbPassword) {println (" login is successful and is redirecting to the home page for you "+ name +" ^ _ ^ ") / / count = 0 return} else {count-= 1 println (" I can't even remember the user name and password, what are you doing all day! You have another chance to circulate the for of ")}.
Scala does not have a structure that corresponds directly to the for (initialize variable; check whether the variable meets a condition; update variable) loop. If you need such a loop, you have two options: one is to use the while loop, and the other is to use the following for statement:
For (I)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.