Scala Series (three) - flow control statements

First, if the conditional expression

Scala in if / else syntax of the Java in the same, the only difference is that, if there is an expression in Scala return value.

object ScalaApp extends App {

  val x = "scala"
  val result = if (x.length == 5) "true" else "false"
  print(result)
  
}

In Java, the need to use every line statement ;indicates the end, but not necessarily in Scala. Unless you write multiple lines of code in a single-line statement.

Second, the block expression

In Scala, can {}block contains a series of expression, the median value of the block is the last block expression.

object ScalaApp extends App {

  val result = {
    val a = 1 + 1; val b = 2 + 2; a + b
  }
  print(result)
}

// 输出: 6

If the last block expression no return value, the return value is the block Unit type.

scala> val result ={ val a = 1 + 1; val b = 2 + 2 }
result: Unit = ()

Third, the while loop expression

Scala and most languages, support whileand do ... whileexpressions.

object ScalaApp extends App {

  var n = 0

  while (n < 10) {
    n += 1
    println(n)
  }

  // 循环至少要执行一次
  do {
    println(n)
  } while (n > 10)
}

Fourth, the loop expression for

The basic loop for use the following:

object ScalaApp extends App {

  // 1.基本使用  输出[1,9)
  for (n <- 1 until 10) {print(n)}

  // 2.使用多个表达式生成器  输出: 11 12 13 21 22 23 31 32 33
  for (i <- 1 to 3; j <- 1 to 3) print(f"${10 * i + j}%3d")

  // 3.使用带条件的表达式生成器  输出: 12 13 21 23 31 32
  for (i <- 1 to 3; j <- 1 to 3 if i != j) print(f"${10 * i + j}%3d")

}

In addition to the basic use, but also you can use the yieldkeyword Vector generated from the for loop, which is called for deriving the formula.

scala> for (i <- 1 to 10) yield i * 6
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(6, 12, 18, 24, 30, 36, 42, 48, 54, 60)

Fifth, exception handling try

And Java as support for try...catch...finallythe statement.

import java.io.{FileNotFoundException, FileReader}

object ScalaApp extends App {

  try {
    val reader = new FileReader("wordCount.txt")
  } catch {
    case ex: FileNotFoundException =>
      ex.printStackTrace()
      println("没有找到对应的文件!")
  } finally {
    println("finally 语句一定会被执行!")
  }
}

It should be noted that because the finally statement will be executed, so do not return values ​​in the statement, otherwise the return value is as a whole try statement return value, as follows:

scala> def g():Int = try return 1 finally  return  2
g: ()Int

// 方法 g() 总会返回 2
scala> g()
res3: Int = 2

Six condition selection expression match

match similar to the switch statement in java.

object ScalaApp extends App {

  val elements = Array("A", "B", "C", "D", "E")

  for (elem <- elements) {
    elem match {
      case "A" => println(10)
      case "B" => println(20)
      case "C" => println(30)
      case _ => println(50)
    }
  }
}

However, the following differences with Java in the switch:

  • Scala supports the statement in the case of any type; whereas in Java case statement only supports integer, enumeration, and string constants;
  • Scala behind each branch statement not need to write break, because the break in the case statement is implicit default there;
  • In Scala match statement that returns a value, and the switch statement in Java is no return value. as follows:
object ScalaApp extends App {

  val elements = Array("A", "B", "C", "D", "E")

  for (elem <- elements) {
    val score = elem match {
      case "A" => 10
      case "B" => 20
      case "C" => 30
      case _ => 50
    }
    print(elem + ":" + score + ";")
  }
}
// 输出: A:10;B:20;C:30;D:50;E:50;

Seven, do not break and continue

Additional note: Scala does not support Java in the break and continue keywords.

Eight, input and output

Scala can be used in print, println, printf printout, which is the same as in Java. If you need to get input from the console, you can use StdIna variety of methods defined.

val name = StdIn.readLine("Your name: ")
print("Your age: ")
val age = StdIn.readInt()
println(s"Hello, ${name}! Next year, you will be ${age + 1}.")

Reference material

  1. Martin Odersky. Scala program (version 3) [M]. Press the electronic industry. 2018-1-1
  2. Kay .S. Horstman Fast learning Scala (2nd Edition) [M]. Press the electronic industry. 2017-7

More big data series can be found GitHub open source project : Big Data Getting Started

Guess you like

Origin www.cnblogs.com/heibaiying/p/11423438.html