Scala (3) Control Structures

A control structure is a block of programming that analyzes variables and selects how to proceed based on given parameters. The control structures in Scala are if, while, for, try, match, and function calls.

1. If expressions:

The if expressions in Scala work just like in many other languages which test the condition and executes one of two code branches depending on whether the condition holds true.

if (diskSize > 250) 
    println("Large disk")
else 
    println("Small disk")

The following syntax shows the if...else if...else expression in Scala:

val diskSize = 500
if (diskSize >= 500)
    println("Large disk")
else if (diskSize < 500 && diskSize > 250)
    println("Middle disk")
else
    println("Small disk")

2. While loops:

The while loop has a condition and a body, and the body is executed over and over as long as the condition holds true.

import scala.util.Random.nextInt

object Main extends App {
    val exam = () => nextInt(100)
    var score = 0

    while (score < 60)
        score = exam()
    println(s"Final score: $score")
}

We can use do...while loop to execute the expressions in the body before we check the condition is true or false.

val exam = () => nextInt(100)
var score = 0

do {
    score = exam()  // execute this expression at least once
} while (score < 60)
println(s"Final score: $score")

3. For expressions:

The Ranges using syntax like "1 to 5" and can iterate through them with a for.

for (i <- 1 to 5)
    println(i)

println((1 to 5).getClass()) // immutable.Range

If you don’t want to include the upper bound of the range in the values that are iterated over, use until instead of to:

for (i <- 1 until 5)
    println(i)

4. Filtering:

You can iterate and filter the elements by adding an if clause inside the for’s curly braces.

val names = List("Ben", "Benson", "Kasey", "Denial")
for {
    name <- names
    if name.startsWith("B")
} println(name)

We can bind the result to a new variable using an equals sign (=) which makes the expression human readble.

val names = List("   Ben   ", "   Benson  ", "  Kasey ", " Denial")
for {
    name <- names
    if name.contains("B")
    trimName = name.trim
} println(trimName)

5. Producing a New Collection with Yield:

Sometimes we want to collect the result of the iteration as List and Scala provides a concise way to do it.

To do so, you prefix the body of the for expression by the keyword yield.

val names = List("Ben", "Benson", "Kasey", " Denial")
val longNames: List[String] = for {
    name <- names
    if name.length >= 5
} yield name
println(longNames) // List(Benson, Kasey,  Denial)

留言

熱門文章