当前位置:网站首页>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语言有所帮助!!!
边栏推荐
- Use kubernetes resource lock to complete your own ha application
- What is the difference between immunohistochemistry and immunohistochemistry?
- EdrawMax思维导图,EdrawMax组织结构图
- MySQL realizes data comparison between two tables by calculating intersection and difference sets
- 华泰证券安全吗
- 【Proteus仿真】4x4矩阵键盘中断方式扫描 +数码管显示
- XML and other file contents in idea cannot be highlighted, and the file becomes gray
- SRAM和DRAM之间的异同
- DO280分配持久性存储
- Advanced installer architect authoring tool
猜你喜欢

Testing until you're 35? The 35 + test will lead to unemployment?
![[temperature detection] thermal infrared image temperature detection system based on Matlab GUI [including Matlab source code 1920]](/img/b7/95601082e67fd31aab80c35d57f273.png)
[temperature detection] thermal infrared image temperature detection system based on Matlab GUI [including Matlab source code 1920]

Teach you how to understand the test environment project deployment

月薪过万的测试员,是一种什么样的生活状态?

ASP. Net based on LAN

To the interface problems we have encountered

PR FAQ: how to retrieve accidentally deleted video and audio in PR?

XML and other file contents in idea cannot be highlighted, and the file becomes gray

手把手教你搞懂测试环境项目部署

Code repetition of reinforcement learning based parameters adaptation method for particlewarn optimization
随机推荐
DO280分配持久性存储
C语言课程设计------食品仓库管理系统
手把手教你搞懂测试环境项目部署
分享自己平时使用的socket多客户端通信的代码技术点和软件使用
Adding, deleting, checking and modifying stack - dynamic memory
Statistical learning method (4/22) naive Bayes
PR FAQ: how to retrieve accidentally deleted video and audio in PR?
I want to buy stocks today, OK? Is it safe to open an account online now?
Installing Oracle database in docker
Business system anti-virus
Magic Quadrant of motianlun's 2021 China Database
【图像处理】基于matlab实现图像曲线调整系统
Analysis of parsing principle of OData metadata request response in SAP ui5 application
AHA C language, C language programming introductory books and PPT (PDF version) download website
ASP. Net based on LAN
独家分析 | 关于简历和面试
Ambiguity between 0 and 1
How to encrypt anti copy program
The metadata request parsing principle of OData XML format applied by SAP ui5 is based on domparser
最新版CorelDRAW Technical Suite2022