当前位置:网站首页>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语言有所帮助!!!
边栏推荐
- 测试只能干到35岁?35岁+的测试就会失业?
- 我想今天买股票,可以么?现在网上开户安全么?
- Exclusive analysis | real situation of software test about resume and interview
- SRAM和DRAM之间的异同
- The function of Schottky diode in preventing reverse connection of power supply
- Is it safe to open a securities account at qiniu business school in 2022?
- Statistical learning method (3/22) k-nearest neighbor method
- 免疫组化和免疫组学之间的区别是啥?
- Basic use of flask Sqlalchemy
- What is the difference between immunohistochemistry and immunohistochemistry?
猜你喜欢

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

Near consensus mechanism

Analysis of sending principle of OData metadata request for SAP ui5 application

SAP ui5 beginner tutorial 24 - how to use OData data model

Day 7 scripts and special effects

Introduction to UE gameplay 44 (animation import FBX and production standard)

Research on VB multi-layer firewall technology - state detection

Pytorch -- use and modification of existing network model

Vulnerability mining | routine in password retrieval

Design and development of VB mine sweeping game
随机推荐
Is it safe to open a securities account at qiniu business school in 2022?
EdrawMax思维导图,EdrawMax组织结构图
How to select database
Battle drag method 1: moderately optimistic and build self-confidence (2)
Docker中安裝Oracle數據庫
Linux7 (centos7) setting oracle11 boot auto start
C language course design - food warehouse management system
Day 7 scripts and special effects
Analysis of sending principle of OData metadata request for SAP ui5 application
Redis data migration (III)
Using autogluon to forecast house price
Share the code technology points and software usage of socket multi client communication
How many locks are added to an update statement? Take you to understand the underlying principles
A full screen gesture adaptation scheme
Analysis of parsing principle of OData metadata request response in SAP ui5 application
基于.NetCore开发博客项目 StarBlog - (13) 加入友情链接功能
Basic use of Sqlalchemy
How to choose source code encryption software
Typescript (7) generic
C语言课程设计------食品仓库管理系统