当前位置:网站首页>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 timesprintf
Output string , adopt % Pass value- Interpolation string :
s"${ Variable name }“
, The prefix fors
Format template string ,f
Floating 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 ,
Any
Is the parent of all data . Any
There are two corresponding subclasses , One is the numeric type (AnyVal
), The other is the reference type (AnyRef
)StringOps
It's right Java MediumString
enhance .Unit
by 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()
, andvoid
It's a keyword- Scala The default is to convert the low precision data type to the high precision data type ( Automatic conversion \ Implicit conversion )
Null
Is 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-128
To127
Short
[2 Bytes ]16 Bit signed complement integer
. The value range is-32768
To32767
Int
[4 Bytes ]32 Bit signed complement integer
. The value range is-2147483648
To2147483647
Long
[8 Bytes ]64 Bit signed complement integer
. The value range is-9223372036854775808
To9223372036854775807
= 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 addedl
perhapsL
- 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
Double
type
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
true
andfalse
- 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 , 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
,Short
andChar
They don't automatically switch to each other .Byte
,Short
,Char
The three of them can calculate , In calculation, it is first converted toInt
type .
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 !!!
边栏推荐
- 11 introduction to CNN
- 大话领域驱动设计——表示层及其他
- 数据分析----numpy快速入门
- MHA switching (recommended operation process)
- Practice of federal learning in Tencent micro vision advertising
- When a programmer is disturbed 10 times a day, the consequences are amazing!
- Scala 基础 (二):变量和数据类型
- 7 user defined loss function
- 油田勘探问题
- Niuke programming problem -- dynamic programming of must brush 101 (a thorough understanding of dynamic programming)
猜你喜欢
In a bad mood, I just write code like this
"C language" question set of ⑩
SAP OData development tutorial - from getting started to improving (including segw, rap and CDP)
补齐短板-开源IM项目OpenIM关于初始化/登录/好友接口文档介绍
Unlock the value of data fusion! Tencent angel powerfl won the "leading scientific and Technological Achievement Award" at the 2021 digital Expo
了解下常见的函数式接口
1-12vmware adds SSH function
TCP congestion control details | 1 summary
牛客编程题--必刷101之动态规划(一文彻底了解动态规划)
Supplement the short board - Open Source im project openim about initialization / login / friend interface document introduction
随机推荐
Codeforces Round #802 (Div. 2)
Supplement the short board - Open Source im project openim about initialization / login / friend interface document introduction
Common properties of XOR and addition
TCP congestion control details | 1 summary
pybullet机器人仿真环境搭建 5.机器人位姿可视化
[207] several possible causes of Apache crash
Redis 迁移(操作流程建议)1
若依如何实现接口限流?
Niuke programming problem -- dynamic programming of must brush 101 (a thorough understanding of dynamic programming)
5 model saving and loading
C语言读取数据
【力扣刷题】二分查找:4. 寻找两个正序数组的中位数
长安链交易防重之布谷鸟过滤器
Mono 的一些实例方法
牛客小白月赛50
Keepalived 实现 Redis AutoFailover (RedisHA)
The first open source MySQL HTAP database in China will be released soon, and the three highlights will be notified in advance
安信证券排名第几位?开户安全吗?
# 补齐短板-开源IM项目OpenIM关于初始化/登录/好友接口文档介绍
对话长安马自达高层,全新产品将在Q4发布,空间与智能领跑日系