当前位置:网站首页>Scala 基礎 (三):運算符和流程控制
Scala 基礎 (三):運算符和流程控制
2022-06-29 01:37:00 【百思不得小趙】
大家好,我是百思不得小趙。
創作時間:2022 年 6 月 27 日
博客主頁: 點此進入博客主頁
—— 新時代的農民工
—— 換一種思維邏輯去看待這個世界
今天是加入CSDN的第1212天。覺得有幫助麻煩點贊、評論、️收藏
一、運算符
Scala中的運算符和Java中的運算符基本相同。
算術運算
+ - * / %,+和-在一元運算錶中示正號和負號,在二元運算中錶示加和减。/錶示整除,只保留整數部分舍弃掉小數部分除此之外,
+也錶示兩個字符串相加
關系運算
== != < > <= >=- 在Java中,
==比較兩個變量本身的值,即兩個對象在內存中的首地址,equals比較字符串中所包含的內容是否相同。 - Scala中的
==更加類似於 Java 中的equals,而eq()比較的是地址
邏輯運算
&& || !,運算得出的結果是一個Boolean值- Scala也支持短路
&& ||
賦值運算
= += -= *= /= %=- 在Scala中沒有
++和--這種語法,通過+=、-=來實現同樣的效果
比特運算
& | ^ ~<< >> >>>,其中<< >>是有符號左移和右移,>>>無符號右移
在 Scala 中其實是沒有運算符的,所有運算符都是方法的調用。
- 當調用對象的方法時,點.可以省略
- 如果函數參數只有一個,或者沒有參數,()可以省略
- 運算符優先級:
(characters not shown below)
* / %
+ -
:
= !
< >
&
^
|
(all letters, $, _)
舉個栗子:
object Test {
def main(args: Array[String]): Unit = {
// 標准加法運算
val i: Int = 1.+(1)
// 當調用對象的方法時,.可以省略
val n: Int = 1 + (1)
// 如果函數參數只有一個,或者沒有參數,()可以省略
val m: Int = 1 + 1
println(i + " , " + n + " , " + m)
}
}
二、流程控制
Scala中的流程控制與其他的編程語言一樣,也包含分支語句、循環語句等。
if - else
基本語法:
if (條件錶達式) {
代碼段
}else if (條件錶達式) {
代碼段
}else {
代碼段
}
舉個栗子:
object Test01_ifelse {
def main(args: Array[String]): Unit = {
println("請輸入你的年齡:")
val age: Int = StdIn.readInt();
if (age >= 18 && age < 30) {
println("中年")
} else if (age < 18) {
println("少年")
} else {
println("老年")
}
}
}
特殊之處:
- 與其他語言不同的是,Scala中的
if else錶達式其實是有返回值的,也可以作為錶達式,定義為執行的最後一個語句的返回值 - Scala 中返回值類型不一致,取它們共同的祖先類型。
- 返回值可以為
Unit類型,此時忽略最後一個錶達式的值,得到() - scala中沒有三元條件運算符,可以用
if (a) b else c替代a ? b : c - 嵌套分支特點相同。
舉個栗子:
object Test01_ifelse {
def main(args: Array[String]): Unit = {
println("請輸入你的年齡:")
// 分支語句的返回值
val result: Unit = if (age >= 18) {
println("恭喜你,成年了")
} else if (age < 18) {
println("不好意思,你還未成年")
} else {
println("你是個人了")
}
println("result:" + result)
val result2: String = if (age >= 18) {
println("恭喜你,成年了")
"恭喜你,成年了"
} else if (age < 18) {
println("不好意思,你還未成年")
"不好意思,你還未成年"
} else {
println("你是個人了")
"你是個人了"
}
println("result:" + result2)
// 不同類型返回值取公共父類
val result3: Any = if (age >= 18) {
println("恭喜你,成年了")
"恭喜你,成年了"
} else if (age < 18) {
println("不好意思,你還未成年")
age
} else {
println("你是個人了")
age
}
println("result:" + result3)
// java中的三元運算 a?b:c scala中使用 if (a) b else c
val res: String = if(age>=18){
"成年"
}else{
"未成年"
}
val res1 = if (age>= 18) "成年" else "未成年"
}
}
for
Scala中的for循環被稱為for的推導式
範圍遍曆:
for (i <- 1 to 10) {
println(i + ":hello world")
}
i錶示循環變量<-相當於將遍曆值賦給變量1 to 10RichInt中的一個方法調用,返回一個Range- 前後閉合
for (i <- 1 until 10) {
println(i + ":hello world")
}
until也是RichInt中的一個方法,返回Range類- 前閉後開
範圍也是一個集合,也可以遍曆普通集合。
for (i <- Array(10, 28, 9, 3, 2)) {
println(i)
}
for (i <- List(10, 28, 9, 3, 2)) {
println(i)
}
for (i <- Set(10, 28, 9, 3, 2)) {
println(i)
}
循環步長:by + 步長
for (i <- 1 to 10 by 2) {
println(i)
}
for (i <- 30 to 10 by -2) {
println(i)
}
循環守衛:
循環守衛,即循環保護式(也稱條件判斷式,守衛)。保護式為 true 則進入循環體內部,為 false 則跳過,類似於 continue。
語法:
for(i <- collection if condition) {
}
等價於:
if (i <- collection) {
if (condition) {
}
}
舉個栗子:
for (i <- 1 to 10) {
if (i != 5) {
println(i)
}
}
for (i <- 1 to 10 if i != 5) {
println(i)
}
循環嵌套:
嵌套循環可以將條件合並到一個for中。
語法:
for (i <- 1 to 3) {
for (j <- 1 to 3) {
println("i = " + i + ",j = " + j)
}
}
等價於:
for (i <- 1 to 3; j <- 1 to 5) {
println("i = " + i + ",j = " + j)
}
舉個栗子:打印乘法錶
object Test03_PracticeMulTable {
def main(args: Array[String]): Unit = {
for (i <- 1 to 9; j <- 1 to i) {
print(s"$j * $i = ${
i * j} \t")
if (j == i) println()
}
}
}
循環引入變量:
循環中的引入變量,但不是循環變量。
for (i <- 1 to 10; j = 10 - i) {
println("i = " + i + ", j = " + j)
}
等價於:
for {
i <- 1 to 10;
j = 10 - i
} {
println("i = " + i + " , j = " + j)
}
循環返回值:
- Scala中for循環默認的返回值為
Unit,實例()。
val a: Unit = for (i <- 1 to 10) {
println(i)
}
- yield:Java中線程的一個方法是yield 錶示線程讓步
- scala中是一個關鍵字 錶示:在當前for循環裏面生成一個集合類型作為返回值,然後返回。
- 將遍曆過程中處理的結果返回到一個新 Vector 集合中,使用 yield 關鍵字。
val b: immutable.IndexedSeq[Int] = for (i <- 1 to 10) yield i * i
// default implementation is Vector, Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
while 和 do…while
While 和 do…While 的使用和 Java 語言中用法相同,不推薦使用,結果類型是Unit。
語法:
while (循環條件) {
循環體(語句)
循環變量迭代
}
do{
循環體(語句)
循環變量迭代
} while(循環條件)
循環中斷
Scala 內置控制結構特地去掉了 break 和 continue,是為了更好的適應函數式編程,推薦使用函數式的風格解决break和continue的功能,而不是一個關鍵字。Scala中使用breakable控制結構來實現 break 和 continue 功能。
拋出异常的方式中斷循環
try {
for (i <- 0 until 5) {
if (i == 3)
throw new RuntimeException
println(i)
}
} catch {
case e: Exception => // 退出循環
}
使用scala中的Breaks中的break方法(相當於只是封裝了异常捕獲),實現异常的拋出和捕捉。
import scala.util.control.Breaks
Breaks.breakable(
for (i <- 0 until 5) {
if (i == 3)
Breaks.break()
println(i)
}
)
本次分享的內容到這裏就結束了,希望對大家學習Scala語言有所幫助!!!
边栏推荐
- Large scale visual relationship understanding
- 一条update语句到底加了多少锁?带你深入理解底层原理
- 牛客网——华为题库(41~50)
- IPFS简述
- 利用kubernetes资源锁完成自己的HA应用
- DO280分配持久性存储
- Analysis of advantages and disadvantages of environment encryption and transparent encryption
- P7 Erkai early know - registration and application creation
- What is the difference between the history and Western blotting
- What kind of life is a tester with a monthly salary of over 10000?
猜你喜欢

Share the code technology points and software usage of socket multi client communication

Analysis of advantages and disadvantages of environment encryption and transparent encryption

第七天 脚本与特效

Research on VB multi-layer firewall technology - state detection

Typescript (5) class, inheritance, polymorphism

What is the difference between the histology and western blotting 两种方法都是进行组织染色的

Teach you how to understand the test environment project deployment

Introduction to super dongle scheme

Day 7 scripts and special effects

Kuboardv3 and monitoring kit installation
随机推荐
QT基於RFID管理系統(可應用於大多數RFID管理系統)
ASP. Net based on LAN
4276. 擅长C
Day 7 scripts and special effects
0和1的歧义问题
Pytorch -- use and modification of existing network model
Analysis of parsing principle of OData metadata request response in SAP ui5 application
Rasa对话机器人之HelpDesk (五)
Test a CSDN free download software
4276. good at C
Learning notes of Lichuang EDA: Copper laying dead zone? isolated island? Dead copper?
TypeScript(6)函数
Introduction to super dongle scheme
Typescript (7) generic
Advanced installer architect authoring tool
How to manage device authorization
Magic Quadrant of motianlun's 2021 China Database
Flask-SQLAlchemy的基本使用
IPFs Brief
Exclusive analysis | about resume and interview