Scala process control

Posted by giannis_athens on Tue, 04 Jan 2022 23:59:53 +0100

Process control

Branch control

Let the program execute selectively. There are three kinds of branch control: single branch, double branch and multi branch

Single branch

if (Conditional expression) {
    // Execute code block
}

When the conditional expression is true, the code of {} will be executed

Double branch

Multi branch

package chapter04

import scala.io.StdIn

object Test01_IfElse {
  def main(args: Array[String]): Unit = {
    print("Please enter your age:")
    val age: Int = StdIn.readInt()

    // Single branch
    if (age > 18) {
      println("adult")
    }

    println("====================")

    // Double branch
    if (age >= 18) {
      println("adult")
    } else {
      println("under age")
    }

    // Multi branch
    if (age <= 6) {
      println("childhood")
    } else if(age <= 18) {
      println("teenagers")
    } else if(age < 40) {
      println("youth")
    } else {
      println("old age")
    }

  }
}

Return value*

In Scala, branch expressions have a return value. This return value is the last sentence in the executed branch statement by default.

package chapter04

import scala.io.StdIn

object Test01_IfElse {
  def main(args: Array[String]): Unit = {
    // Return value
    val sex: Char = 'male'
    val result = if (sex == 'male') {
      println('male')
    } else if(sex == 'female') {
      println('female')
    } else {
      println("Lesson XX ")
    }

    println(s"result: ${result}")

    var resultStr: String = if (sex == 'male') {
      println('male')
      "male"
    } else if(sex == 'female') {
      println('female')
      "female"
    } else {
      println("Lesson XX ")
      "Lesson XX "
    }

    println(s"resultStr: ${resultStr}")
  }
}

Nested branch

If statements can be nested in if statements

for loop control

Scala also provides many features for the common control structure of the for loop. These features of the for loop are called for derivation or for expression.

Range data cycle To

Basic grammar
for(i < -1 to 3) {
    // code
}

Range data loop Unitl

Cycle guard

Basic grammar
for(i <- 1 to 3 if i != 2) {
    // code
}

Circular guard, i.e. circular protection type. If the protected type is true, it enters the loop; If false, skip, similar to continue.

Therefore, the above code is equivalent to

for (i <- 1 to 3) {
    if(i != 2) {
        // code
    }
}

Cycle step

Nested loop

Basic grammar
for(i <- 1 to 3; j <- 1 to 3) {
    // code
}

This syntax is equivalent to:

for(i <- 1 to 3) {
    for(j <- 1 to 3) {
        // code
    }
}

Introducing variables

Basic grammar
for(i <- 1 to 3; j = 4 - i) {
    // code
}

When there are multiple expressions in a row of for inference formula, it should be added; To block logic

The for derivation has an unwritten Convention: use parentheses when the for derivation contains only a single expression.

Loop return value

Return the results processed in the traversal process to a new Vector collection, using the yield keyword.

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

This is rarely used in development.

Reverse printing

while loop control

While and do The use of while is the same as in the Java language

while

A loop condition is an expression that returns a Boolean value

A while loop is a statement that is judged before execution

Different from the for statement, the while statement does not return a value, that is, the result of the whole while statement is of type Unit.

Because there is no return value in while, it is inevitable to use variables when using this statement to calculate and return results, and variables need to live outside the while loop, which is equivalent to the internal of the loop affecting external variables, so it is not recommended.

do...while

package chapter04

object Test05_WhileLoop {
  def main(args: Array[String]): Unit = {
    var a: Int = 10
    while (a >= 1) {
      println("This is a while loop:" + a)
      a -= 1
    }

    var b: Int = 0
    do {
      println("This is a do while loop:" + b)
      b += 1
    } while (b > 0)
  }
}

Cycle 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. The breakable control structure is used in scala to implement break and continue functions.

package chapter04

import scala.util.control.Breaks

object Test06_Break {
  def main(args: Array[String]): Unit = {
    // Exit the loop by throwing an exception
    try {
      for (i <- 0 until 5) {
        if (i == 3) {
          throw new RuntimeException
        }
        println(i)
      }
    } catch {
      case e: RuntimeException => // Do nothing, just throw an exception and exit the loop
    }

    println("End of cycle")

    // 2. Use the break method in the Breaks class in Scala to throw and catch exceptions
    Breaks.breakable(
      for (i <- 1 until 10) {
        if (i == 3)
          Breaks.break()
        println(i)
      }
    )

  }
}