当前位置:网站首页>Scala 基础 (三):运算符和流程控制
Scala 基础 (三):运算符和流程控制
2022-06-27 23:22:00 【InfoQ】
一、运算符
+ - * / %,+和-在一元运算表中示正号和负号,在二元运算中表示加和减。
/表示整除,只保留整数部分舍弃掉小数部分
- 除此之外,
+也表示两个字符串相加
== != < > <= >=
- 在Java中,
==比较两个变量本身的值,即两个对象在内存中的首地址,equals比较字符串中所包含的内容是否相同。
- Scala中的
==更加类似于 Java 中的equals,而eq()比较的是地址
&& || !,运算得出的结果是一个Boolean值
- 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)
}
}
二、流程控制
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
forfor 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)
}
truefalsecontinuefor(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
Unitwhile (循环条件) {
循环体(语句)
循环变量迭代
}
do{
循环体(语句)
循环变量迭代
} while(循环条件)
循环中断
breakcontinuebreakcontinuebreakablebreakcontinue try {
for (i <- 0 until 5) {
if (i == 3)
throw new RuntimeException
println(i)
}
} catch {
case e: Exception => // 退出循环
}
import scala.util.control.Breaks
Breaks.breakable(
for (i <- 0 until 5) {
if (i == 3)
Breaks.break()
println(i)
}
)
边栏推荐
- pytorch_lightning.utilities.exceptions.MisconfigurationException: You requested GPUs: [1] But...
- Centos8 operation record command version Yum redis MySQL Nacos JDK
- 零基础多图详解图神经网络
- Overview of drug discovery-01 overview of drug discovery
- Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)
- Want to open an account to buy stock, is it safe to open an account on the Internet?
- Data analysts too hot? Monthly income 3W? Tell you the true situation of this industry with data
- Google Earth engine (GEE) -- an error caused by the imagecollection (error) traversing the image collection
- The practice of dual process guard and keeping alive in IM instant messaging development
- 评价——秩和比综合评价
猜你喜欢

机器学习笔记 - 时间序列作为特征
![[Niuke discussion area] Chapter 4: redis](/img/53/f8628c65890f1c68cedab9008c1b84.png)
[Niuke discussion area] Chapter 4: redis
![[description] solution to JMeter garbled code](/img/13/01682d08cbcb47be5d7c21304ef901.png)
[description] solution to JMeter garbled code

Ten MySQL locks, one article will give you full analysis

【嵌入式基础】串口通信

Web3 technology initial experience and related learning materials

药物发现综述-03-分子设计与优化

评价——灰色关联分析

电商转化率这么抽象,到底是个啥?

Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
随机推荐
完全二叉树的节点个数[非O(n)求法 -> 抽象二分]
Chapitre 4: redis
Transformer论文逐段精读
Ten thousand words long article understanding business intelligence (BI) | recommended collection
Proe/creo product structure design - continuous research
Why stainless steel swivel
Deepmind | pre training of molecular property prediction through noise removal
Is it safe to open an online futures account?
LMSOC:一种对社会敏感的预训练方法
Database query optimization: master-slave read-write separation and common problems
Adobe Premiere foundation - sound adjustment (volume correction, noise reduction, telephone tone, pitch shifter, parameter equalizer) (XVIII)
【开源】开源系统整理-考试问卷等
Maimai hot post: Why are big factories keen on making wheels?
无人机专用滑环定制要求是什么
Is there any risk in opening an account for flush stock? Is it safe for flush to open an account
大尺寸导电滑环市场应用强度如何
FB、WhatsApp群发消息在2022年到底有多热门?
Set collection usage
SQL Server 2016 detailed installation tutorial (with registration code and resources)
OS模块与OS.path 模块的学习