Control flow structures in Scala are used to control the order in which statements are executed in a program. Scala supports several control flow structures, including conditional statements, loops, and pattern matching. Here’s a brief overview of these structures:
1. Conditional statements: Scala supports two types of conditional statements: if-else and match expressions.
– if-else: The if-else statement in Scala works similarly to that in other programming languages. Here’s an example:
` val x = 10 if (x > 5) { println("x is greater than 5") } else { println("x is less than or equal to 5") }
– match expressions: Match expressions are a powerful feature in Scala that allow you to match a value against a set of patterns. Here’s an example:
` val x = 2 val result = x match { case 1 => "one" case 2 => "two" case _ => "other" } println(result) // prints "two"
2. Loops: Scala supports several types of loops, including for loops, while loops, and do-while loops.
– for loops: For loops in Scala are similar to those in other programming languages, but they can be used to iterate over a wide range of collections, including arrays, lists, and tuples. Here’s an example:
` val myArray= Array(1, 2, 3, 4, 5) for (x <- myArray) { println(x) }
- while loops: While loops in Scala work similarly to those in other programming languages. Here's an example:
` var x = 10 while (x > 0) { println(x) x -= 1 }
- do-while loops: Do-while loops in Scala work similarly to those in other programming languages. Here's an example:
` var x = 10 do { println(x) x -= 1 } while (x > 0)
3. Pattern matching: Pattern matching is a powerful feature in Scala that allows you to match a value against a set of patterns and execute code based on the match. Here's an example:
- match expressions:
` val x = 2 val result = x match { case 1 => "one" case 2 => "two" case _ => "other" } println(result) // prints "two"
Overall, Scala's control flow structures are powerful and expressive, and they allow developers to write code that is concise and easy to read.