当前位置:网站首页>Scala Basics (II): variables and data types
Scala Basics (II): variables and data types
2022-06-26 16:24:00 【Think hard of Xiao Zhao】
Hello everyone , I can't think of Xiao Zhao .
Creation time :2022 year 6 month 24 Japan
Blog home page : Click here to enter the blog home page
—— Migrant workers in the new era
—— Look at the world with another kind of thinking logic
Today is to join CSDN Of the 1210 God . I think it's helpful and troublesome. I like it 、 Comment on 、️ Collection
List of articles
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 var
character string
Basic grammar
- Keyword is
String - adopt
+Connection No *Used to copy a string multiple timesprintfOutput 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 bagStdIn.readLine()Read stringStdIn.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 .

Integer types
Byte[1 Bytes ]8 Bit signed complement integer. The value range is-128To127Short[2 Bytes ]16 Bit signed complement integer. The value range is-32768To32767Int[4 Bytes ]32 Bit signed complement integer. The value range is-2147483648To2147483647Long[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 numbersDouble[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 valuenullNothing: 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 , The system first 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 !!!
边栏推荐
猜你喜欢

Pybullet robot simulation environment construction 5 Robot pose visualization

Ten thousand words! In depth analysis of the development trend of multi-party data collaborative application and privacy computing under the data security law

How to implement interface current limiting?

The details of the first pig heart transplantation were fully disclosed: human herpes virus was found in the patient, the weight of the heart doubled after death, and myocardial cell fibrosis

首例猪心移植细节全面披露:患者体内发现人类疱疹病毒,死后心脏重量翻倍,心肌细胞纤维化丨团队最新论文...

Dialogue with the senior management of Chang'an Mazda, new products will be released in Q4, and space and intelligence will lead the Japanese system

用Attention和微调BERT进行自然语言推断-PyTorch

牛客编程题--必刷101之动态规划(一文彻底了解动态规划)

What is the process of switching C # read / write files from user mode to kernel mode?

Arduino UNO + DS1302简单获取时间并串口打印
随机推荐
【蓝桥杯集训100题】scratch辨别质数合数 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第15题
油田勘探问题
对话长安马自达高层,全新产品将在Q4发布,空间与智能领跑日系
4 custom model training
Structure the graduation project of actual combat camp
Detailed explanation of cookies and sessions
What is the process of switching C # read / write files from user mode to kernel mode?
mha 切换(操作流程建议)
JS教程之Electron.js设计强大的多平台桌面应用程序的好工具
Anaconda3 installation tensorflow version 2.0 CPU and GPU installation, win10 system
国内首款开源 MySQL HTAP 数据库即将发布,三大看点提前告知
数据分析----numpy快速入门
『C语言』题集 of ⑩
7 user defined loss function
R language uses cor function to calculate the correlation matrix for correlation analysis, uses corrgram package to visualize the correlation matrix, reorders rows and columns using principal componen
Angel 3.2.0 new version released! Figure the computing power is strengthened again
Least squares system identification class II: recursive least squares
Some instance methods of mono
JS教程之使用 ElectronJS、VueJS、SQLite 和 Sequelize ORM 从 A 到 Z 创建多对多 CRUD 应用程序
【小5聊】毕业8年,一直在追梦的路上