当前位置:网站首页>Fundamentals of scala (3): operators and process control
Fundamentals of scala (3): operators and process control
2022-06-28 02:11:00 【InfoQ】
One 、 Operator
+ - * / %
,+
and-
Show positive and negative signs in the unary operation table , To express addition and subtraction in a binary operation .
/
To divide or divide , Keep only integer parts and discard decimal parts
- besides ,
+
It also means adding two strings
== != < > <= >=
- stay Java in ,
==
Compare the values of the two variables themselves , The first address of two objects in memory ,equals
Compare whether the contents contained in the string are the same .
- Scala Medium
==
More similar to Java Mediumequals
, andeq()
The comparison is the address
&& || !
, The result of the operation is Boolean value
- Scala Short circuit is also supported
&& ||
= += -= *= /= %=
- stay Scala There is no
++
and--
This grammar , adopt+=
、-=
To achieve the same effect
& | ^ ~
<< >> >>>
, among<< >>
Is a signed shift left and right ,>>>
unsigned right shift
- When an object's method is called , spot . It can be omitted
- If there is only one function parameter , Or no parameters ,() It can be omitted
- Operator priority :
(characters not shown below)
* / %
+ -
:
= !
< >
&
^
|
(all letters, $, _)
object Test {
def main(args: Array[String]): Unit = {
// Standard addition operation
val i: Int = 1.+(1)
// When an object's method is called ,. It can be omitted
val n: Int = 1 + (1)
// If there is only one function parameter , Or no parameters ,() It can be omitted
val m: Int = 1 + 1
println(i + " , " + n + " , " + m)
}
}
Two 、 Process control
if - else
if ( Conditional expression ) {
Code segment
}else if ( Conditional expression ) {
Code segment
}else {
Code segment
}
object Test01_ifelse {
def main(args: Array[String]): Unit = {
println(" Please enter your age :")
val age: Int = StdIn.readInt();
if (age >= 18 && age < 30) {
println(" middle-aged ")
} else if (age < 18) {
println(" juvenile ")
} else {
println(" The elderly ")
}
}
}
- Different from other languages ,Scala Medium
if else
An expression actually has a return value , It can also be used as an expression , Defined as the return value of the last statement executed
- Scala Inconsistent return value types in , Take their common ancestor type .
- The return value can be
Unit
type , At this point, the value of the last expression is ignored , obtain()
- scala There is no ternary conditional operator in , It can be used
if (a) b else c
replacea ? b : c
- Nested branches have the same characteristics .
object Test01_ifelse {
def main(args: Array[String]): Unit = {
println(" Please enter your age :")
// The return value of the branch statement
val result: Unit = if (age >= 18) {
println(" congratulations , Grown up ")
} else if (age < 18) {
println(" sorry , You're underage ")
} else {
println(" You're a man ")
}
println("result:" + result)
val result2: String = if (age >= 18) {
println(" congratulations , Grown up ")
" congratulations , Grown up "
} else if (age < 18) {
println(" sorry , You're underage ")
" sorry , You're underage "
} else {
println(" You're a man ")
" You're a man "
}
println("result:" + result2)
// Return values of different types take the public parent class
val result3: Any = if (age >= 18) {
println(" congratulations , Grown up ")
" congratulations , Grown up "
} else if (age < 18) {
println(" sorry , You're underage ")
age
} else {
println(" You're a man ")
age
}
println("result:" + result3)
// java The ternary operation in a?b:c scala Use in if (a) b else c
val res: String = if(age>=18){
" adult "
}else{
" A minor "
}
val res1 = if (age>= 18) " adult " else " A minor "
}
}
for
for
for
for (i <- 1 to 10) {
println(i + ":hello world")
}
i
Represents a cyclic variable
<-
It is equivalent to assigning traversal value to variable
1 to 10
RichInt
A method call in , Return to oneRange
- Close back and forth
for (i <- 1 until 10) {
println(i + ":hello world")
}
until
It's alsoRichInt
One of the methods in , returnRange
class
- Before closed after opening
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 + step
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 in for The default return value of the loop is
Unit
, example()
.
val a: Unit = for (i <- 1 to 10) {
println(i)
}
- yield:Java One method of threading in is yield Indicates a thread concession
- scala Is a keyword in Express : At present for The loop generates a collection type as the return value , Then return .
- == Return the results processed during traversal to a new Vector Collection , Use yield keyword .==
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 and do......while
Unit
while ( The loop condition ) {
The loop body ( sentence )
Loop variable iteration
}
do{
The loop body ( sentence )
Loop variable iteration
} while( The loop condition )
Cycle break
break
continue
break
continue
breakable
break
continue
try {
for (i <- 0 until 5) {
if (i == 3)
throw new RuntimeException
println(i)
}
} catch {
case e: Exception => // Exit loop
}
import scala.util.control.Breaks
Breaks.breakable(
for (i <- 0 until 5) {
if (i == 3)
Breaks.break()
println(i)
}
)
边栏推荐
- Qu'est - ce que la numérisation? Qu'est - ce que la transformation numérique? Pourquoi les entreprises choisissent - elles la transformation numérique?
- Ten thousand words long article understanding business intelligence (BI) | recommended collection
- LMSOC:一种对社会敏感的预训练方法
- [sylixos] I2C device driver creation and use
- [Yocto RM]9 - QA Error and Warning Messages
- pytorch_ lightning. utilities. exceptions. MisconfigurationException: You requested GPUs: [1] But...
- Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
- General process after reference layer reboot
- 网络爬虫是什么
- 【牛客討論區】第四章:Redis
猜你喜欢
Numpy----np. reshape()
Web3 technology initial experience and related learning materials
类的初始化与回调的用法
Adobe Premiere foundation - sound adjustment (volume correction, noise reduction, telephone tone, pitch shifter, parameter equalizer) (XVIII)
Numpy----np.tile()函数解析
Appium自动化测试基础— 补充:App的包名(appPackage)和启动名(appActivity)
Shardingsphere-proxy-5.0.0 establish MySQL read / write separation connection (6)
Chapitre 4: redis
pytorch_ lightning. utilities. exceptions. MisconfigurationException: You requested GPUs: [1] But...
Solon 1.8.3 release, cloud native microservice development framework
随机推荐
Jenkins - 邮件通知 Email Notification 插件
Drug interaction prediction based on learning size adaptive molecular substructure
机器学习笔记 - 时间序列作为特征
面试官问:JS的this指向
Google Earth engine (GEE) -- an error caused by the imagecollection (error) traversing the image collection
【sylixos】NEW_1 型字符驱动示例
[Yocto RM]1 - System Requirements
学习 pickle
药物发现综述-03-分子设计与优化
深入解析kubernetes controller-runtime
面试官问:能否模拟实现JS的new操作符
Xctf attack and defense world misc wage earner advanced zone
Import the data table in MySQL into Excel
The practice of dual process guard and keeping alive in IM instant messaging development
【牛客讨论区】第四章:Redis
Cesium 获取屏幕所在经纬度范围
[Yocto RM]8 - OpenEmbedded Kickstart (.wks) Reference
要搞清楚什么是同步,异步,串行,并行,并发,进程,线程,协程
1382. balancing binary search tree - General method
How to read a paper