Scala has similar conditional expressions as available in other programming languages.
1. If Statement
The statement inside the if block will only execute when the expression is true.
Syntax:
if(expression) { // statements }
Note : In Scala, adding a semicolon(;) at the end of statements is optional and generally avoided, unlike Java .
Example :
val color = "RED"
if (color == "BLUE") {
println("Hey! This is Red Color")
}
println("Hey i skipped the if condition!")
Output :
val color: String = RED
Hey i skipped the if condition!
2. If else Statement
In the if-else statement, either if or else will execute based on the result of the expression. If the expression is true, then the statement inside the if block will execute; otherwise, statements inside the else block will execute.
Syntax :
If (expression) {
//Statement or statements
} else {
//statement or statements
}
Example :
val age =17
if (age>18) {
println("Candidate is eligible for voting")
} else {
println("Candidate is not eligible for voting")
}
Output :
val age: Int = 17
Candidate is not eligible for voting
3. If else ladder
Syntax:
If (expression) {
// statements
} else if(expression) {
//statements
} else {
// statements
}
Example:
val marks = 75
val result = if (marks < 40) {
"The student has failed"
} else if (marks < 50) {
"Student has scored Grade D"
} else if (marks < 60) {
"Student has scored Grade C"
} else if (marks < 75) {
"Student has scored Grade B"
} else {
"Student has scored Grade A"
}
Output:
val marks: Int = 75
val result: String = Student has scored Grade A
4. Nested If else
This expression is used when one if-else is needed inside another if-else block. It is said to be nested if-else.
Example:
val number1 = 2
val number2 = 3
val number3 = 2
if(number1 == number2) {
if (number1 == number3) {
"All three numbers are equal"
}
else {
"Numbers are unequal"
}
}
else {
"Numbers are unequal"
}
Output:
val number1: Int = 2
val number2: Int = 3
val number3: Int = 2
val res3: String = Numbers are unequal
Another example:
val marks = 175
val result = if (marks >= 0 && marks <= 100) {
if (marks < 40) {
"The student has failed"
} else if (marks < 50) {
"Student has scored Grade D"
} else if (marks < 60) {
"Student has scored Grade C"
} else if (marks < 75) {
"Student has scored Grade B"
} else {
"Student has scored Grade A"
}
} else
"Invalid marks"
Output:
val marks: Int = 175
val result: String = Invalid marks