Scala if-else conditional expression

 246 total views,  3 views today

Welcome to Scala series. In this tutorial, you will learn about Scala if-else conditional expression

In any programming language, the if-else conditional expression is widely used for testing expressions and do further operations based on the results.

Scala also supports if-else statements and these statements test the boolean condition which can either return true or false. Based on the outcome of the expression, further logic will be executed.

Simple if statement

Syntax

if(Condition) {
  //Perform the neccessary logic
}

Example

var flag = true;
if (flag) {
    println("I am true...now perform")
}

if-else statement

Syntax

if(Condition) {
  //Perform the neccessary logic
}else{
  //Perform the neccessary logic
}

Example

var flag = true;
if (flag) {
    println("I am true...now perform")
}else{
    println("I am false")
}

Nested if-else statement

Syntax

if(Condition1) {
  //Perform the neccessary logic
}else if(condition2) {
  //Perform the neccessary logic
}else if(condition3) {
  //Perform the neccessary logic
}else {
  //Perform the neccessary logic
}

Example

var i: Int = 10;

 if (i < 3) {
      //TODO
 } else if (i > 4 && i < 7) {
      //TODO
 } else if (i >= 7 && i < 9) {
      //TODO
 } else {
      //TODO
 }

Conclusion

I hope this Scala tutorial on if-else conditional expression was useful and you were able to understand with a detailed example. Please leave a comment below and give us a thumbs up!.

Reference :https://docs.scala-lang.org/style/control-structures.html

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.