Control Structures
Scala has the basic control structures you’d expect to find in a programming language, as follows:
- if/then/else
- for loops
- try/catch/finally
Scala also has several unique control structures, as follows:
- match expressions
- for expressions
These control structures are explained in detail next.
if/then/else Structure
Three common code examples
if (x == y) {
doSomething()
}
// another style
if (x == y) doSomething()
Copy the code
if (x == y) {
doSomething()
} else {
doSomethingElse()
}
Copy the code
if (x == y) {
doSomethingForXY()
} else if (x == z) {
doSomethingForXZ()
} else {
doSomethingElse()
}
Copy the code
An if expression always returns a result
One nice feature of Scala is that the if structure always returns a result, but you can ignore the result it returns, as in the code example above. But it is more common to refer to a variable, especially in functional programming, as shown in the following code example:
val minValue = if (x < y) x else y
Copy the code
Looking at code like this, it’s easy to think of “ternary operators.” Yes, it does the same thing as ternary operators, so Scala doesn’t introduce special ternary operators
Note: Expression oriented programming
When every expression you write returns a result, we call this style “expression oriented Programming,” or EOP, which was the style in the last code example.
Conversely, lines of code that do not return a result are called “statements”. The purpose of these statements is to produce side effect 1.
if (a == b) doSomething() // This is a statements, is for side-effects
Copy the code
for loops Structure
The simplest use of the for loop is to iterate over elements in a container. Here is an example of code:
val nums = Seq(1.2.3.4) // given a sequence of integers
for (n <- nums) println(n)
Copy the code
We can also use the for loop for summing. Here is an example of code for summing the first 100 items:
var i = 0
var sum = 0
for (i <- 1 to 100) sum += i
println(sum) / / 5050
Copy the code
The for loop can also be used to iterate over a Map, as shown in the following code example:
val scores = Map(
"Andrew" -> 100."Tom" -> 95."Pater" -> 60
)
for ((name, score) <- scores) println(s"Name: $name, Score: $score")
Copy the code
The foreach method
We can also use the foreach method in Scala to iterate over and print elements in a container. The foreach method is available in most Of Scala’s container classes, including Map. Here is a common code example:
val nums = Seq(1.2.3.4)
nums.foreach(println)
Copy the code
val scores = Map(
"Andrew" -> 100."Tom" -> 95."Pater" -> 60
)
scores.foreach {
case (name, score) => println(s"Name: $name, Score: $score")}Copy the code
for Expressions
If you can remember the “expression oriented programming “(EOP) that we used in the “if/then/else” Structure section and the difference between expressions and statements, you can see that we used the for and foreach methods as a” side effect “tool in the last section, We use them and println to print out the values of the elements in the container.
Once you start working in Scala, you’ll find that in functional programming you can use for expressions that are much more powerful than for statements. It’s important to distinguish between for statements and for expressions. The for statement is used for scenarios that produce side effects (such as print-outs), and the for expression is used for scenarios that generate containers from existing containers, as shown in the following code example for the for expression:
val nums = Seq(1.2.3.4 )
val doubleNums = for (n <- nums) yield n * 2 // doubleNums: (2, 4, 6, 8)
// using a block of code
val doubleNums = for (n <- nums) yield { n * 2 } // doubleNums: (2, 4, 6, 8)
Copy the code
Tips:
-
Behind yield can be either a brief expression, also can be a complex code block (use {} enclose the part), generally it is recommended to use a simple expression, if you have to write more complicated logic, lines of code blocks, consider the complex logic abstract out a method, so the yield is still behind a simple expression, It just becomes a method call
-
Notice the yield keyword here, what it means is THAT I’m going to produce a new container based on the one I already have, which means “produce”
match Expressions
Scala designs a “match” expression that is similar to the Switch statement in Java, as shown in the following code example:
val i = 5
val numberDescription = i match {
case 1= >"equals one"
case 2= >"equals two"
case 11= >"equals three"
case_ = >"else number"
}
println(numberDescription) // else number
Copy the code
As you can see in the code example, when “I” matches a case, the string corresponding to the case is returned, The resulting returned string points to a new variable, “numberDescription”, where “_” represents any other value (except 1, 2, or 11), which is the default case, acting like “default” in Java.
Tip:
- The “match” expression in Scala also returns a value, not just a side effect, which is functional programming and friendly
As an aside – a quick look at how methods are defined in Scala
The following code example defines a simple method for converting values:
def convertBooleanToStringMessage(bool: Boolean) :String = {
if (bool) "true" else "false"
}
val result = convertBooleanToStringMessage(true) // true
Copy the code
This method is used to convert the Boolean variable of the input parameter to the corresponding string variable
Use the “match” expression as the body of the method
We can use the expression “match” refactoring “convertBooleanToStringMessage” method in the last section of, under the code examples are as follows:
def convertBooleanToStringMessage(bool: Boolean) :String = bool match {
case true= >"true"
case false= >"false"
}
Copy the code
In addition, a single “case” statement of Scala’s “match” expression can define multiple matching rules, as shown in the following example:
val evenOrOdd = i match {
case 1 | 3 | 5 | 7 | 9 => println("odd")
case 2 | 4 | 6 | 8 | 10 => println("even")
case _ => println("some other number")}Copy the code
Or “|” said here, which is used to combine multiple “value” matching rules, say that because if it is multiple “or” “expression” matching rules, we need to use “| |”, this after the follow-up will be displayed in the sample.
Use “if” expressions in “case” statements
The combination of an if expression and a case statement makes “pattern matching “2 even more powerful, as shown in the following code example:
count match {
case 1 => println("one, a lonely number")
case x if x == 2 || x == 3 => println("two's company, three's a crowd")
case x if x > 3 => println("4+, that's a party")
case _ => println("i'm guessing your number is zero or less")}Copy the code
Here “| |” said or to combine multiple “expression” matching rules, we can see in the second case statement, the program will point to the reference count variable x, and then use the if to judge x (this is actually the count value) is equal to 2 or 3, this is a case statement in the use of the if expression.
Here is an example of code for matching numeric ranges:
i match {
case a if 0 to 9 contains a => println("0-9 range: " + a)
case b if 10 to 19 contains b => println("10-19 range: " + b)
case c if 20 to 29 contains c => println("20-29 range: " + c)
case _ => println("Hmmm...")}Copy the code
Using a reference field in an if expression is a common scenario in the real world, as shown in the following code:
i match {
case x if (x.symbol == "XYZ" && x.price < 20) => buy(x)
case x if (x.symbol == "XYZ" && x.price > 50) => sell(x)
case x => doNothing(x)
}
Copy the code
try/catch/finally Structure
You can use “try/catch/finally” to catch and manage exceptions. Case statements are used in Scala to match the different types of exceptions that can occur. Here is a basic code example:
var fileText = ""
try {
fileText = openAndReadAFile(fileName)
} catch {
case e: FileNotFoundException => println("Couldn't find that file.")
case e: IOException => println("Had an IOException trying to read that file")}Copy the code
In this example, the openAndReadAFile method opens and reads a file, and then points the read result to the variable fileText. Scala operates on the file using Java’s java.io.* class, So the exceptions most likely to be thrown in this process are FileNotFoundException and IOException, which are caught and handled in the sample catch block.
In exception catching and handling, finally statements are typically used to close resources, such as file resources, database connections, etc., as shown in the following code example:
try {
// your scala code here
}
catch {
case e: FooException => handleFooException(e)
case e: BarException => handleBarException(e)
case_ :Throwable => println("Got some other kind of Throwable exception")}finally {
// your scala code here, such as closing a database connection
// or file handle
}
Copy the code
One of the best things about Scala’s “try/catch/finally” syntax is that for different types of exception handling, you can just use case matching in the catch block. This is pretty neat, and will make your code consistent and readable.
Referrences
- [1] Side Effects, en.wikipedia.org/wiki/Side_e…
- [2] the Pattern Matching, en.wikipedia.org/wiki/Patter…
It is not easy to create, I hope you can give me a lot of support, this article will be updated every week, we will see you next time.
From zero volume to well | (original)
Focus not to get lost
If you have any questions, please feel free to contact me through wechat