chapter goals
- Master the definition and use of variables and strings
- Master the division of data types and the content of data type conversion
- Master the keyboard entry function
- Understand constants and identifiers in Scala
1. Output statement and semicolon
1.1 Output statement
Method 1: Newline output
Format: println(Write the data you want to print to the console);
Method 2: output without wrapping
Format: print(Write the data you want to print to the console);
Note: Both println() and print() statements can print multiple values at the same time. The format is: println(value1, value2, value3...)
1.2 Semicolons
In Scala statements, the semicolon at the end of a single line of code can be written or not. If multiple lines of code are written on one line, the semicolon in the middle cannot be omitted, and the semicolon of the last line of code can be omitted.
Example:
println("Hello, Scala!") //The final semicolon can be written or not //If multiple lines of code are written on one line, the semicolon of the previous statement must be written, and the semicolon of the last statement can be omitted. println("Hello"); println("Scala")
2. Constants in Scala
2.1 Overview
A constant refers to a quantity whose value cannot be changed during the running of the program.
2.2 Classification
- Literal constants (commonly used are the following)
- integer constant
- floating point constant
- character constant
- string constant
- boolean constant
- empty constant
- Custom constants (explained later)
2.3 Code Demonstration
//integer constant println(10) //floating point constant println(10.3) //Character constant, the value should be enclosed in single quotes println('a') //String constant, the value should be enclosed in double quotes println("abc") //Boolean constant, the only values are true and false println(true) //empty constant println(null)
3. Variables in Scala
3.1 Overview
We will define variables every day when we write scala programs in the future, so what is a variable and how is it defined?
Variable refers to the amount whose value can change during the execution of the program. The definition format is as follows:
3.2 Syntax format
Java variable definition
int a = 0;
In scala, you can use val or var to define variables, the syntax is as follows:
val/var variable name:variable type = initial value
in
- val defines a variable that cannot be reassigned, that is, a custom constant.
- var defines a variable that can be reassigned
Note: When defining variables in scala, the type is written after the variable name
3.3 Examples
**Requirement:** Define a variable to save a person's name "tom"
step
- Open the scala interpreter
- Define a variable of type string to hold the name
Reference Code
scala> val name:String = "tom" name: String = tom
3.4 The difference between val and var variables
example
Reassign the name variable to Jim, and observe its running results
Reference Code
scala> name = "Jim" <console>:12: error: reassignment to val name = "Jim"
example
Use var to redefine the variable to save the name "tom", and try to reassign it to Jim, and observe its running results
Reference Code
scala> var name:String = "tom" name: String = tom scala> name = "Jim" name: String = Jim
Note: Use val first to define variables, and only use var if the variable needs to be reassigned
3.5 Using type inference to define variables
scala's syntax is more concise than Java, and we can use a more concise way to define variables.
example
Use a cleaner syntax to define a variable to hold a person's name "tom"
Reference Code
scala> val name = "tom" name: String = tom
scala can automatically infer the type of the variable according to the value of the variable, so that the code is more concise.
4. string
scala provides a variety of ways to define strings. In the future, we can choose the most convenient way to define according to our needs.
- use double quotes
- Use interpolation expressions
- use triple quotes
4.1 Using double quotes
grammar
val/var variable name = "string"
example
There is a person whose name is "hadoop", please print his name and the length of his name.
Reference Code
scala> println(name + name.length) hadoop6
4.2 Using interpolation expressions
In scala, you can use interpolation expressions to define strings, effectively avoiding the concatenation of a large number of strings.
grammar
val/var variable name = s"${variable/expression}string"
Notice:
- add s before the definition string
- In strings, you can use ${} to refer to variables or write expressions
example
Please define several variables and save them separately: "zhangsan", 23, "male", define a string and save these information.
Printout: name=zhangsan, age=23, sex=male
Reference Code
scala> val name = "zhangsan" name: String = zhangsan scala> val age = 23 age: Int = 23 scala> val sex = "male" sex: String = male scala> val result = s"name=${name}, age=${age}, sex=${sex}" result: String = name=zhangsan, age=23, sex=male scala> println(result) name=zhangsan, age=23, sex=male
4.3 Using triple quotes
If there is a large section of text that needs to be saved, you can use triple quotes to define the string. For example: save a large section of SQL statement. Everything between the three quotes will be the value of the string.
grammar
val/var variable name = """String 1 string 2"""
example
Define a string to save the following SQL statement
select * from t_user where name = "zhangsan"
print the SQL statement
Reference Code
val sql = """select | * | from | t_user | where | name = "zhangsan"""" println(sql)
4.4 Extension: lazy assignment
In the big data development of enterprises, sometimes very complex SQL statements are written, and these SQL statements may have hundreds or even thousands of lines. If these SQL statements are directly loaded into the JVM, there will be a large memory overhead. How to solve this problem?
When some variables hold large data, these data do not need to be loaded into the JVM memory immediately. You can use lazy assignment to improve efficiency.
Grammar format:
lazy val/var variable name = expression
example
The following complex SQL statement needs to be executed in the program, and we hope to load it only when this SQL statement is used.
"""insert overwrite table adm.itcast_adm_personas select a.user_id, a.user_name, a.user_sex, a.user_birthday, a.user_age, a.constellation, a.province, a.city, a.city_level, a.hex_mail, a.op_mail, a.hex_phone, a.fore_phone, a.figure_model, a.stature_model, b.first_order_time, b.last_order_time, ... d.month1_hour025_cnt, d.month1_hour627_cnt, d.month1_hour829_cnt, d.month1_hour10212_cnt, d.month1_hour13214_cnt, d.month1_hour15217_cnt, d.month1_hour18219_cnt, d.month1_hour20221_cnt, d.month1_hour22223_cnt from gdm.itcast_gdm_user_basic a left join gdm.itcast_gdm_user_consume_order b on a.user_id=b.user_id left join gdm.itcast_gdm_user_buy_category c on a.user_id=c.user_id left join gdm.itcast_gdm_user_visit d on a.user_id=d.user_id;"""
Reference Code
scala> lazy val sql = """insert overwrite table adm.itcast_adm_personas | select | a.user_id, .... | left join gdm.itcast_gdm_user_buy_category c on a.user_id=c.user_id | left join gdm.itcast_gdm_user_visit d on a.user_id=d.user_id;""" sql: String = <lazy>
5. Identifier
5.1 Overview
In actual development, we will write a lot of code, and there will definitely be variables, methods, classes, etc. in these codes. How should they be named? This requires the use of identifiers. Identifiers are used to give variables and methods , class names etc. Identifiers in Scala are very similar to identifiers in Java.
5.2 Naming rules
- Must be composed of uppercase and lowercase English letters, numbers, underscore _, dollar sign $, any combination of these four parts.
- Numbers cannot begin with.
- Cannot have the same name as a keyword in Scala.
- It's best to be known.
5.3 Naming convention
-
Variables or methods: Starting from the second word, the first letter of each word is capitalized, and all other letters are lowercase (small camel case).
zhangSanAge, student_Country, getSum
-
Class or trait (Trait): the first letter of each word is capitalized, and all other letters are all lowercase (Upper CamelCase)
Person, StudentDemo, OrderItems
-
Package: All lowercase, usually the company's domain name is reversed, and the multi-level packages are separated by .
com.itheima.add, cn.itcast.update
6. Data Types
6.1 Brief introduction
Data types are used to constrain the value range of variables (constants). Scala is also a strongly typed language, and most of the data types in it are the same as Java. We mainly learn
- Some usages that are different from Java
- Inheritance system of data types in scala
6.2 Data Types
basic type | type description |
---|---|
Byte | 8-bit signed integer |
Short | 16-bit signed integer |
Int | 32-bit signed integer |
Long | 64-bit signed integer |
Char | 16-bit unsigned Unicode characters |
String | Sequence of type Char (string) |
Float | 32-bit single-precision floating-point number |
Double | 64-bit double-precision floating-point number |
Boolean | true or false |
Note the difference between the scala type and Java
[!NOTE]
- All types in scala start with an uppercase letter
- Use Int instead of Integer for shaping
- You can define variables in scala without writing the type, and let the scala compiler automatically infer
- The default integer type in Scala is Int, and the default floating point type is: Double
6.3 The Scala Type Hierarchy
Types of | illustrate |
---|---|
Any | The parent class of all types, which has two subclasses AnyRef and AnyVal |
AnyVal | Parent class of all numeric types |
AnyRef | **The parent class of all object types (reference types)** |
Unit | Indicates empty, Unit is a subclass of AnyVal, it has only one instance {% em %}() {% endem %} It is similar to void in Java, but scala is more object-oriented than Java |
Null | Null is a subclass of AnyRef, which means it is a subclass of all reference types. Its instance is {% em %}null{% endem %} can assign null to any object type |
Nothing | Subclasses of all types cannot directly create instances of this type. When a method throws an exception, the return type is Nothing, because Nothing is a subclass of all classes, so it can be assigned to any type |
6.4 Thinking questions
Is there something wrong with the following code?
val b:Int = null
Scala will explain the error: Null type cannot be converted to Int type, indicating that Null type is not a subclass of Int type
7. Type conversion
7.1 Overview
When a Scala program is performing operations or assignments, the data type values with a small range will be automatically converted to data type values with a large range, and then calculated. For example: 1 + 1.1 The result of the operation is a Double type of 2.1. And some Sometimes, we will involve some actions similar to "rounding". We need to convert a decimal to an integer before calculating. These are the type conversions in Scala.
Type conversion in Scala is divided into type conversion of value type and type conversion of reference type. Here we will focus on: type conversion of value type.
Type conversion of value types is divided into:
- automatic type conversion
- cast
7.2 Automatic type conversion
-
Explanation
A data type value with a small range will be automatically converted to a data type value with a large range. This action is called: automatic type conversion.
Automatic type conversion from small to large: Byte, Short, Char -> Int -> Long -> Float -> Double
-
sample code
val a:Int = 3 val b:Double = 3 + 2.21 //Because the calculation is performed on the values of int type and double type, the final result is: Double type val c:Byte = a + 1 //Writing in this way will cause an error, because the final calculation result is data of type Int, and it will definitely not work to assign it to type Byte.
7.3 Mandatory type conversion
-
Explanation
A data type value with a large range can be converted into a data type value with a small range through a certain format (coercive conversion function). This action is called: forced type conversion.
Note: When using mandatory type conversion, it may cause loss of precision!
-
Format
val/var variable name:type of data = specific value.toXxx //Xxx represents the data type you want to convert to
- Reference Code
val a:Double = 5.21 val b:Int = a.toInt
7.4 Mutual conversion between value type and String type
1. Data of value type is converted to String type
Format one:
val/var variable name:String = value type data + ""
Format two:
val/var variable name:String = value type data.toString
example
Convert data of type Int, Double, Boolean to its corresponding string form.
Reference Code:
val a1:Int = 10 val b1:Double = 2.1 val c1:Boolean = true //Method 1: Realized by concatenating with an empty string val a2:String = a1 + "" val b2:String = b1 + "" val c2:String = c1 + "" //Method 2: Realized by the toString function val a3:String = a1.toString val b3:String = b1.toString val c3:String = c1.toString
2. String type data is converted into its corresponding value type
Format:
val/var variable name:value type = string value.toXxx //Xxx represents the data type you want to convert to
Notice:
- The data of String type is converted into data of Char type, the method is a bit special, instead of calling toChar, but toCharArray
- This point can be understood for now, and we will explain it in detail later
need:
Convert string-type integers, floating-point numbers, and Boolean data into their corresponding value type data.
Reference Code:
val s1:String = "100" val s2:String = "2.3" val s3:String = "false" //Convert string type data to its corresponding: Int type val a:Int = s1.toInt //Convert string type data to its corresponding: Double type val b:Double = s2.toDouble //Convert string type data to its corresponding: Boolean type val c:Boolean = s3.toBoolean
8. Keyboard entry
8.1 Overview
The data we mentioned above are all "dead" and fixed data written by us, so the user experience is not particularly good. If these data are entered by users and then we receive them through code, it will be very fun. This is the "keyboard entry" function in Scala that we will learn next.
8.2 Steps to use
-
Guide package
Format: import scala.io.StdIn
-
Receive the data entered by the user's keyboard through StdIn.readXxx()
Receive string data: StdIn.readLine()
Receive integer data: StdIn.readInt()
8.3 Examples
-
Prompt the user to enter a string, and receive the printout.
println("Please enter a string: ") val str = StdIn.readLine() println("The content of the string you entered is: " + str)
-
Prompt the user to enter an integer, and receive the printout.
println("Please enter an integer: ") val num = StdIn.readInt() println("The number you entered is: " + num)
9. Case: Greeting
9.1 Overview
After chatting for so long, hurry up and say hello to your friends.
Requirements: Prompt user to enter his/her name and age, receive and print.
9.2 Specific steps
- Prompt the user to enter a name.
- Receive the name entered by the user.
- Prompt the user to enter their age.
- Receive the age entered by the user.
- Print the data entered by the user (name and age) to the console.
9.3 Reference code
//1. Prompt the user to enter their name. println("Please enter your name: ") //2. Receive the name entered by the user. val name = StdIn.readLine() //3. Prompt the user to enter their age. println("Please enter your age: ") //4. Receive the age entered by the user. val age = StdIn.readInt() //5. Print the data entered by the user (name and age) to the console. println(s"Hello everyone, My name is ${name}, this year, I ${age}Years old, It's a pleasure to study with you Scala!") for: " + str)
-
Prompt the user to enter an integer, and receive the printout.
println("Please enter an integer: ") val num = StdIn.readInt() println("The number you entered is: " + num)
9. Case: Greeting
9.1 Overview
After chatting for so long, hurry up and say hello to your friends.
Requirements: Prompt user to enter his/her name and age, receive and print.
9.2 Specific steps
- Prompt the user to enter a name.
- Receive the name entered by the user.
- Prompt the user to enter their age.
- Receive the age entered by the user.
- Print the data entered by the user (name and age) to the console.
9.3 Reference code
//1. Prompt the user to enter their name. println("Please enter your name: ") //2. Receive the name entered by the user. val name = StdIn.readLine() //3. Prompt the user to enter their age. println("Please enter your age: ") //4. Receive the age entered by the user. val age = StdIn.readInt() //5. Print the data entered by the user (name and age) to the console. println(s"Hello everyone, My name is ${name}, this year, I ${age}Years old, It's a pleasure to study with you Scala!")