Control structures (if, while, for). in scala

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-20 14:32:28 Viewed : 256


Scala provides various control structures, including if-else expressions, while loops, and for comprehensions, which allow you to control the flow of execution in your programs. Here is an overview of these control structures in Scala:

1. if-else Expressions: Scala is if-else expressions can be used to conditionally execute blocks of code based on Boolean conditions. The syntax is as follows:

scala
val x = 10 if (x > 5) { println("x is greater than 5") } else { println("x is less than or equal to 5") }
output:
x is greater than 5

2. while Loops: Scala supports while loops, which allow you to execute a block of code repeatedly as long as a given condition is true. Here is an example:

scala
var x = 0 while (x < 5) { println(s"x is $x") x += 1 }
output:
x is 0 x is 1 x is 2 x is 3 x is 4

3. for Comprehensions: Scala is for comprehensions provide a concise way to iterate over collections, arrays, or ranges. You can use for comprehensions to perform operations on each element of a collection. Here is an example:

scala
val numbers = List(1, 2, 3, 4, 5) for (num <- numbers) { println(num) }
output:
1 2 3 4 5

You can also use for comprehensions to filter elements and perform more complex operations on collections.

Scala is control structures are similar to those in other programming languages but provide additional flexibility and power due to Scala is functional programming features. Additionally, Scala encourages the use of immutable data structures and functional programming constructs, which can lead to more concise and readable code when using these control structures. Understanding how to use these control structures effectively is essential for writing clear and maintainable Scala code.

Search
Related Articles

Leave a Comment: