当前位置:网站首页>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 ,equalsCompare 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 elseAn 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
Unittype , 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 creplacea ? 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
forfor for (i <- 1 to 10) {
println(i + ":hello world")
}
iRepresents a cyclic variable
<-It is equivalent to assigning traversal value to variable
1 to 10RichIntA method call in , Return to oneRange
- Close back and forth
for (i <- 1 until 10) {
println(i + ":hello world")
}
untilIt's alsoRichIntOne of the methods in , returnRangeclass
- 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)
}
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 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
Unitwhile ( The loop condition ) {
The loop body ( sentence )
Loop variable iteration
}
do{
The loop body ( sentence )
Loop variable iteration
} while( The loop condition )
Cycle break
breakcontinuebreakcontinuebreakablebreakcontinue 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)
}
)
边栏推荐
- Lmsoc: a socially sensitive pre training method
- 类的初始化与回调的用法
- Qu'est - ce que la numérisation? Qu'est - ce que la transformation numérique? Pourquoi les entreprises choisissent - elles la transformation numérique?
- 药物发现综述-03-分子设计与优化
- Capacitor
- 【sylixos】NEW_ Example of type 1 character drive
- 要搞清楚什么是同步,异步,串行,并行,并发,进程,线程,协程
- 766. 托普利茨矩阵
- Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
- Numpy----np. reshape()
猜你喜欢

MapReduce elementary programming practice
![[Niuke discussion area] Chapter 4: redis](/img/53/f8628c65890f1c68cedab9008c1b84.png)
[Niuke discussion area] Chapter 4: redis
![[embedded foundation] serial port communication](/img/b7/18fec20e2d5fa5f226c6f8bb1e93d2.png)
[embedded foundation] serial port communication

What is digitalization? What is digital transformation? Why do enterprises choose digital transformation?

Drug interaction prediction based on learning size adaptive molecular substructure

Class initialization and callback usage

如何理解 Transformer 中的 Query、Key 与 Value

LMSOC:一种对社会敏感的预训练方法

Numpy----np.tile()函数解析

基于AM335X开发板 ARM Cortex-A8——Acontis EtherCAT主站开发案例
随机推荐
JS random number (random number decimal)
Review of drug discovery-02-prediction of molecular properties
[Yocto RM] 4 - Source Directory Structure
Numpy----np. reshape()
【sylixos】i2c设备驱动创建和使用
766. toplitz matrix
如何理解 Transformer 中的 Query、Key 与 Value
Google Earth engine (GEE) -- an error caused by the imagecollection (error) traversing the image collection
一张图弄懂 MIT,BSD,Apache几种开源协议之间的区别
Numpy----np.meshgrid()
1382. 将二叉搜索树变平衡-常规方法
评价——秩和比综合评价
Cesium Click to draw polygons (dynamically draw polygons)
Cesium 点击绘制多边形(动态绘制多边形)
Web3 technology initial experience and related learning materials
centos8-操作记录-命令版-yum-redis-mysql-nacos-jdk
Adobe Premiere Basics - common video effects (cropping, black and white, clip speed, mirroring, lens halo) (XV)
Qu'est - ce que la numérisation? Qu'est - ce que la transformation numérique? Pourquoi les entreprises choisissent - elles la transformation numérique?
Original | 2025 to achieve the "five ones" goal! The four products of Jiefang power are officially released
The interviewer asked: this point of JS