1. Declare variables
1.1 Complete Definition
In Scala, we use val or var to define variables in the following syntax:
// val defines variables that cannot be reassigned
// var defines variables that can be reassigned
val/varVariable name: Variable type = initial value eg:val name:String = "jack"
Copy the code
[!TIP]
- In Scala, the defined variable type is written after the variable name
- Scala statements do not require a semicolon at the end
- Preferred to use
val
Define a variable and use it only if it needs to be reassignedvar
1.2 Type inference – Define variables
In Scala, we do not specify the type of a variable when we define it. Scala specifies the type of a variable based on its value.
The sample
// This is the complete format for defining variables
scala> val name:String = "Jack"
name: String = Jack
// The type of the variable is omitted when defining the variable
scala> val name = "Jack"
name: String = Jack
scala> val age = 23
age: Int = 23
Copy the code
1.3 Lazy assignment
When large data needs to be saved, but does not need to be loaded into JVM memory immediately. Lazy assignment can be used to improve efficiency.
Syntax format:
lazy val/varVariable name = expressionCopy the code
Reference code
scala> lazy val sql = """ | select | * | from | user | """
sql: String = <lazy> // Is not loaded into the JVM
Copy the code
Now that you know how to define variables, you may have noticed that in Scala, we don’t use semicolons after variable declarations and assignments. We only use semicolons when we use multiple statements in the same line of code
2. The string
2.1 Use double quotation marks
val/varVariable name = "string" eg:val name = "tom"
Copy the code
2.2 Interpolation expression
val/varThe variable name =s"${variable/expression}The string"
eg:
val name = "jack"
val name1 = s"${name}"
Copy the code
[!TIP]
- Before the string is defined
s
- In a string, you can use
The ${}
To reference a variable or write an expression
scala> val name = "jack"
name: String = jack
scala> val age = 23
age: Int = 23
${$} = ${$}
scala> val log = s"name=${name}, age=${age}"
info: String = name=zhangsan, age=30
Copy the code
2.3 Use triple quotation marks
val/varThe variable name =String 1 String 2""
// Can be used to store a large amount of data, but lazy assignment is not covered here
Copy the code