If Else statements in Scala
The ability to change the behavior of a piece of code which is based on certain information in the environment is known as conditional code flow. The conditional logic in Scala is primarily based on the scala if .. else structure.
Watch this Informatica video
if Statement
If statement is used to test a condition, if a condition is true then the code inside the if the statement is executed otherwise that code is not executed.
Syntax
if(Boolean_expression)
{
// Body of if
}
e.g.
object Intellipaat {
def main(args: Array[String]) {
var I = 20;
if( I==20 ){
println("If statement is executed");
}
}
}
Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
If the statement is executed
if-else Statement
If Else is also used to test a condition, if a condition is true then the code inside the if the statement is executed otherwise else part is executed.
Syntax
if(Boolean_expression){
// Body of if statement
}else{
// Body of else statement
}
e.g.
object Intellipaat {
def main(args: Array[String]) {
var I = 20;
if( I<=20 ){
println("If statement is executed");
}
else
{
println("Else statement is executed");
}
}
}
Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
If the statement is executed
if…else if…else Statement
After if statement else it is used to check the multiple conditions.
Syntax
if(Boolean_expression1){
// Body of if statement
}
else if(Boolean_expression2){
//Body of else if
}
else{
// Body of else statement
}
e.g.
object Intellipaat {
def main(args: Array[String]) {
var I = 20;
if( I<20 ){
println("If statement is executed");
}
else if (I ==20)
{
println("Else if statement is executed");
}
else
{
println("Else statement is executed");
}
}
}
Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
Else if statement is executed
Nested If Statement
It contains multiple if-else conditions. It is used to check multiple conditions. This statement is like executing an if statement inside an else statement.
Syntax
if(Boolean_expression1){
//Body of if statement
if(Boolean_expression2)
{
//Body of nested if
}
}
…
else{
//Body of else statement
}
e.g.
object Intellipaat {
def main(args: Array[String]) {
var I = 20;
if( I<=20 ){
println("If statement is executed");
if(i<30)
{
println("Nested if statement is executed");
}
}
else
{
println("Else statement is executed");
}
}
}
Compile and execute the above program:
scalac Intellipaat.scala
scala Intellipaat
Output
If statement is executed
Nested if statement is executed
Get 100% Hike!
Master Most in Demand Skills Now!
Living without break and continue
Scala does not use a break and continue commands because these commands do not mesh well with function literals. The simple approach is to replace every continue statement with an if statement and every break statement with a boolean variable. The Boolean variable indicates whether the enclosing while loop should continue.