Course Content
Introduction to Scala
Introduction to Scala
If-Else Chain
Understanding Else If
It is often the case when we have multiple conditions and for each separate condition a separate code block should be executed. That's where the else if
statement comes into play.
Let's first take a look at the flowchart which combines if
, else if
and else
:
Here's an example to make things clear. Suppose I want to determine whether I have enough money on the balance (balance
) to buy a certain number of books (booksNumber
) given their price (bookPrice
). If my balance is greater than or equal to the total cost of the books (totalCost
), I can afford them. Moreover, if the difference between my balance and the total cost of the books is less than or equal to 100
, a discount can be made and I'll be able to buy them. If the difference is greater, then I cannot afford the books.
Main
object Main { def main(args: Array[String]): Unit = { val bookPrice = 120 val booksNumber = 25 var totalCost = bookPrice * booksNumber var balance = 2890 if (balance >= totalCost) { balance -= totalCost println("I can afford them") } else if (totalCost - balance <= 100) { balance = 0 println("A discount can be made") } else { println("I cannot afford them ") } println("The current balance is " + balance) } }
More Else If
In fact, you can have an arbitrary number of else if
statements in case you want to execute different code for different conditions. Basically, you just stack them vertically in the desired order like this:
Main
if (condition1) { // code to execute } else if (condition2) { // code to execute } else if (condition3) { // code to execute } // You can as many conditions as you want else { // code to execute }
As you can see, the approach is rather simple and straightforward.
Nested Conditional Statements
As a matter of fact, the code blocks within conditional statements (if
, else if
or else
) can also contain other conditional statements which are called nested conditional statements. The level of nesting can also be arbitrarily large.
Main
if (condition1) { // The nesting can be arbitrarily deep if (...) { // code to execute } else if (...) { //code to execute if (...) { //code to execute } } else (...) { //code to execute } } else if (condition2) { if (...) { // code to execute } } else { // code to execute }
Overall, using else if
we can make our code much more flexible by adding more alternatives to the conditions.
Thanks for your feedback!