当前位置:网站首页>Scala Basics (II): variables and data types
Scala Basics (II): variables and data types
2022-06-26 02:13:00 【InfoQ】
One 、 Variables and constants
How to define ?
var Variable name [: Variable type ] = Initial value
val Constant names [: constant type ] = Initial value
Take a chestnut :
var a: Int = 10;
val b: Int = 22;
// Variable types can be omitted
var a = 10;
val b = 22;
because Scala It's a functional programming language , So you don't need variables where you can use constants .
Important conclusions :
- When variables are declared , Type can be omitted , Compiler automatically infers , That is type derivation .
- Static type , A type cannot be modified after it has been given or derived .
- When variables and constants are declared , There must be an initial value .
- var The modified variable is variable ,val Modifier constants are immutable .
- Reference type constant , Cannot change the object pointed to by a constant , You can change the fields of an object .
- Don't to ; At the end of the sentence ,scala The compiler automatically recognizes the end of a statement .
Specification for identifier naming
- Start with a letter or underscore , Followed by a letter 、 Numbers 、 Underline , and Java The grammar is the same
- Scala You can start with an operator , And contains only the operator (+ - * / # ! etc. )
- What's special :scala Any string enclosed in backquotes , Even if it's Scala keyword (39 individual ) It's fine too .
Take a chestnut :
val hello = ""
var Helo = ""
var _abc=123
var -+/% = "hello"
var `if` = 123
Scala Keyword set in :•
package, import, class, object, trait, extends, with, type, for•
private, protected, abstract, sealed, final, implicit, lazy, override•
try, catch, finally, throw•
if, else, match, case, do, while, for, return, yield•
def, val, var•
this, super•
new•
true, false, null And Java Here's the difference :
object trait with implicit match yield def val varcharacter string
Basic grammar
- Keyword is
String
- adopt
+Connection No
*Used to copy a string multiple times
printfOutput string , adopt % Pass value
- Interpolation string :
s"${ Variable name }“, The prefix forsFormat template string ,fFloating point number for formatting template ,%The following is the formatted content
- Raw output :
raw" Output content ${ Variable name }", The output result is output as is
- Output statement :
print( Output content )、println()、printf()
- Three quotation marks indicate a string , Keep the original format output of multiline string .
"""......."""
Take a chestnut :
val name: String = "lisi" + " ";
val age: Int = 12
println(name * 3)
printf("%d Year old %s be at table ", age, name)
// Format template string
println(s"${age} Year old ${name} be at table ")
val num: Double = 2.26054
println(s"this number is ${num}")
println(f"this num is ${num}%2.2f")
println(raw"this num is ${num}%2.2f")
val sql =
s"""
|select *
| from student
| where name = ${name}
| and
| age > ${age}
|""".stripMargin
println(sql)
Keyboard entry
Basic grammar
import scala.io.StdIn,StdIn stay IO It's a bag
StdIn.readLine()Read string
StdIn.readShort()
StdIn.readDouble()
- .....................
Take a chestnut :
object Test04_StdInt {
def main(args: Array[String]): Unit = {
println(" Please enter your name :")
val name = StdIn.readLine()
println(" Please enter your age :")
val age = StdIn.readInt()
println(s" welcome ${age} Of ${name}, Light copy system !!!")
}
}
File input and output :
import scala.io.Source
import java.io.PrintWriter
import java.io.File
object Test05_FileIO {
def main(args: Array[String]): Unit = {
// 1. Reading data from a file
Source.fromFile("src/main/resources/test.txt").foreach(print)
// 2. Write data to file
val writer = new PrintWriter(new File("src/main/resources/put.txt"))
writer.write("hello scala from java")
writer.close()
}
}
Two 、 data type
Java Data types in
- Basic types :
char、byte、short、int、long、float、double、boolean
- The corresponding packaging class :
Character、Byte、Short、Integer、Long、Float、Double、Boolean
- because Java There are basic types , And the basic type is not a real object ,Java Not purely object-oriented .
Scala Data types in
- Scala All data in a database are objects ,
AnyIs the parent of all data .
AnyThere are two corresponding subclasses , One is the numeric type (AnyVal), The other is the reference type (AnyRef)
StringOpsIt's right Java MediumStringenhance .
Unitby Scala A data type in , Corresponding Java Mediumvoid, Indicates that the method does not return a value , There is only one singleton , Output as string(), andvoidIt's a keyword
- Scala The default is to convert the low precision data type to the high precision data type ( Automatic conversion \ Implicit conversion )
NullIs a type , only There is one right Elephant yesnull. It's all reference types (AnyRef) Subclasses of .
Nothing, Is a subclass of all data types , Use when a function has no explicit return value , Because in this way we can throw the return value , Return to any variable or function .<center> Data type chart ( Source network ~)</center>

Integer types
Byte[1 Bytes ]8 Bit signed complement integer. The value range is-128To127
Short[2 Bytes ]16 Bit signed complement integer. The value range is-32768To32767
Int[4 Bytes ]32 Bit signed complement integer. The value range is-2147483648To2147483647
Long[8 Bytes ]64 Bit signed complement integer. The value range is-9223372036854775808To9223372036854775807= 2 Of (64-1) Power -1
- Each integer type has a fixed representation range and field length
- Scala The default data type is
Int, Long integers need to be addedlperhapsL
- Converting a high-precision number to a low-precision number requires a cast :
val b3: Byte = (1 + 10).toByte
Take a chestnut :
val al: Byte = 127
val a2: Byte = -128
val a3 = 12
val b1: Byte = 10
val b2: Byte = (10 + 20)
println(b2)
val b3: Byte = (b1 + 10).toByte
Floating point type
Float[4] 32 position , IEEE 754 Standard single precision floating point numbers
Double[8] 64 position IEEE 754 Standard double precision floating point numbers
- The default is
Doubletype
Take a chestnut :
val f1: Float = 1.232f
val d2 = 12.987
Character type
- The character type is
Char, Represents a single character
- Character constants are in single quotes ' ' A single character enclosed .
- Escape character :
\t 、\n、\\、\”
Boolean type
- Booolean Only values of type data are allowed
trueandfalse
- Take up a byte
Take a chestnut :
val isTrue = true
val isFalse: Boolean = false
println(isTrue)
Empty type
Unit: It means no value There is only one instance value , It's written in()
Null: Null Type has only one instance valuenull
Nothing: Confirm that there is no normal return value , It can be used Nothing To specify the return type
Take a chestnut :
def m2(n: Int): Int = {
if (n == 0)
throw new NullPointerException
else
return n
}
Type conversion
- Principle of automatic promotion : There are many types of data mixed operations , Firstly, the system automatically converts all data into the data type with high precision , And then calculate .
- Error will be reported when high-precision data is transferred to the precision .
Byte,ShortandCharThey don't automatically switch to each other .
Byte,Short,CharThe three of them can calculate , In calculation, it is first converted toInttype .
Take a chestnut :
val a1: Byte = 10;
val b1: Long = 20L;
val result1: Long = a1 + b1
println(result1)
Cast
- Cast :
toByte、toInt、......
'aaa'.toInt 2.2.toInt
- There is a loss of precision
- Sum of values String Conversion between :
Basic type of value +" "、s1.toInt、s1.toFloat、s1.toDouble、s1.toByte
Take a chestnut :
val n1: Int = 2.5.toInt
println(n1)
val n2: Int = (2.6 + 3.7).toInt
println(n2)
// Change the value to String
val a: Int = 27
val s: String = a + " "
println(s)
//String Convert to numeric
val m: Int = "12".toInt
val f: Float = "12.4".toFloat
val f2: Int = "12.6".toFloat.toInt
println(f2)
This article ends here , I hope it helped you !!!
边栏推荐
- ARM流水线如何提高代码执行效率
- Back to top case
- shell学习记录(三)
- Sqlyog shortcut keys
- Command of gun make (4) rule
- Output Lua print to the cocos2d console output window
- One minute to understand the difference between synchronous, asynchronous, blocking and non blocking
- Eureka注册信息配置备忘
- 为 ServiceCollection 实现装饰器模式
- Create OpenGL window
猜你喜欢
随机推荐
Redis-链表
Consumer of microservices
Markov decision process (MDP): Blackjack problem (mc-es)
Other codes,, VT,,, K
Raspberry pie + AWS IOT introductory experiment
Ardiuno智能电蚊拍
Computer shortcut keys commonly used by experts
Abnova CSV monoclonal antibody solution
Small ball bouncing against the wall
VTK initialization code learning 1
Unexpected output super efficiency SBM model matlab code
qtvtkvs2015测试代码
A lost note for konjaku beginner
General introduction to gun make (2)
shell curl 执行脚本,带传参数,自定义参数
购买了fastadmin小程序助手但是问题工单中无法发布工单
shell学习记录(四)
High performance and high availability computing architecture based on microblog comments
基于邻接矩阵的广度优先遍历
keda 2.7.1 scaledJob 代码简要分析








