Learn Scala_day01_ Chapter 6 notes

Scala process control

Branch control if else

The if else expression in Scala actually has a return value. The specific return value depends on the last line of the code body that meets the conditions.

object TestIfElse {
 def main(args: Array[String]): Unit = {
 println("input age")
 var age = StdIn.readInt()
 val res :String = if (age < 18){
 "childhood"
 }else if(age>=18 && age<30){
 "middle age"
 }else{
 "old age"
 }
 println(res)
 } }

The return value types in Scala are inconsistent. Take their common ancestor type.

object TestIfElse {
def main(args: Array[String]): Unit = {
 println("input age")
 var age = StdIn.readInt()
 val res:Any = if (age < 18){
 "childhood"
 }else if(age>=18 && age<30){
 "middle age"
 }else{
 100
 }
 println(res)
 } }

Ternary operators in Java can be implemented with if else. If there is only one line of logical code in braces {}, braces can be omitted. If braces are omitted, if works only on the nearest line of logical code.

object TestIfElse {
 def main(args: Array[String]): Unit = {
 // Java
// int result = flag?1:0
 // Scala
 println("input age")
 var age = StdIn.readInt()
 val res:Any = if (age < 18) "childhood" else "adult" 
 "It doesn't work"
 println(res)
 } }

Switch branch structure
In Scala, there is no Switch, but pattern matching. The knowledge points involved in pattern matching are relatively comprehensive, which will be mentioned later.

Scala loop control

Scala wide data loop (To):

for(i <- 1 to 3){
 print(i + " ")
}
println()

(1) i represents the variable of the loop, < - specify to
(2) i will cycle from 1-3 and close back and forth

Scala range data cycle (Until):

for(i <- 1 until 3) {
 print(i + " ")
}
println()

(1) The difference between this method and the previous one is that i is from 1 to 3-1
(2) Even the range of front closing and rear opening

Scala loop guard:

for(i <- 1 to 3 if i != 2) {
 print(i + " ")
}
println()

(1) Circular guard, i.e. circular protection type (also known as conditional judgment type, guard). If the protected type is true, it will enter the loop body, and if it is false, it will skip, similar to continue.
(2) The above code is equivalent

for (i <- 1 to 3){
if (i != 2) {
print(i + " ")
} }

Scala cycle step:

for (i <- 1 to 10 by 2) {
 println("i=" + i)
}

Note: by indicates the step size

Scala nested loop:

for(i <- 1 to 3; j <- 1 to 3) {
 println(" i =" + i + " j = " + j)
}

Note: there is no keyword, so it must be added after the range; To block logic
The above code is equivalent

for (i <- 1 to 3) {
 for (j <- 1 to 3) {
 println("i =" + i + " j=" + j)
 } }

explain:
(1) When there are multiple expressions in a row of for derivation, it is necessary to add; To block logic
(2) The for derivation has an unwritten Convention: use parentheses when the for derivation contains only a single expression,
When multiple expressions are included, there is usually one expression per line, and curly braces are used instead of parentheses, as shown below

for {
 i <- 1 to 3
j = 4 - i
} {
 println("i=" + i + " j=" + j)
}

The above code is equivalent to

for (i <- 1 to 3) {
 var j = 4 - i
 println("i=" + i + " j=" + j)
}

Scala loop return value:

val res = for(i <- 1 to 10) yield i
println(res)

Description: return the results processed in the traversal process to a new Vector set, and use the yield keyword.
Note: it is rarely used in development.
Example:

object TestFor {
 def main(args: Array[String]): Unit = {
 var res = for(i <-1 to 10) yield {
 i * 2
 }
 println(res)
 } }

Output result:
Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

Scala reverse printing:
If you want to print a set of data in reverse order, you can use reverse.
Example:

for(i <- 1 to 10 reverse){
 println(i)
}

While and do... While loop control:
While and do... While are used in the same way as in the Java language.

Scala loop interrupt
Scala's built-in control structure specifically removes break and continue in order to better adapt to functional programming. It is recommended to use functional style to solve the functions of break and continue, rather than a keyword. Scala uses breakable control structure to realize break and continue functions.
1. Exit the cycle in an abnormal way

def main(args: Array[String]): Unit = {
 try {
 for (elem <- 1 to 10) {
 println(elem)
 if (elem == 5) throw new RuntimeException
 }
 }catch {
 case e:Exception =>
 }
 println("Normal end of cycle")
}

2. Use Scala's own functions to exit the loop

import scala.util.control.Breaks
def main(args: Array[String]): Unit = {
 Breaks.breakable(
 for (elem <- 1 to 10) {
 println(elem)
 if (elem == 5) Breaks.break()
 }
 )
 println("Normal end of cycle")
}

3. Omit Breaks

import scala.util.control.Breaks._
object TestBreak {
 def main(args: Array[String]): Unit = {
 breakable {
 for (elem <- 1 to 10) {
 println(elem)
 if (elem == 5) break
 }
 }
 
 println("Normal end of cycle")
 } }

Exercise: printing nine layer demon tower in Scala language (three ways)

object test {
  def main(args: Array[String]): Unit = {
    for(i <- 1 to 9){  //Mode 1
      val starts = 2 * i - 1
      val spaces = 9 - i
      println(" " * spaces + "*" * starts)
    }
    for(i <- 1 to 9;starts = 2 * i - 1;spaces = 9 - i){ //Mode 2
      println(" " * spaces + "*" * starts)
    }
    for (starts <- 1 to 17 by 2 ; spaces = (17 - starts) /2 ){ //Mode 3
      println(" " * spaces + "*" * starts)
    }
  } }

Keywords: Scala Back-end

Added by tegwin15 on Thu, 27 Jan 2022 23:30:11 +0200