Scala IF ELSE - Scala

What is Scala - If else?

This following chapter takes you through the conditional construction statements in the Scala programming. Below diagram is the general form of a typical decision making IF...ELSE structure found in most of the programming languages.

Flow Chart

The below diagram explains the flow chart for the conditional statement.

Flowchart

if Statement

‘if’ statement consists of Boolean expression which is followed by one or more statements.

Syntax

The syntax of an ‘if’ statement is as follows.

If the Boolean expression evaluates to true then the block of code which is written inside the ‘if’ expression will be executed. If not, then the first set of code after the end of the ‘if’ expression will be executed.

Try the below given example program to understand the conditional expressions (if expression) in Scala Programming Language.

Example

Save the above program in the Demo.scala. The following commands will be used to compile and execute this program.

Command

Output

If-else Statement

An ‘if’ statement can generally be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax

The syntax of a if...else is -

Try the following example program to understand conditional statements (if- else statement) in Scala Programming Language.

Example

Save the above program in Demo.scala. The following commands can be used to compile and execute this program.

Command

Output

If-else-if-else Statement

An 'if' statement can always be followed by optional 'else if...else' statement, which is very useful to test the various conditions using the single if...else if statement.

While using if , else if , else statements there are few points to keep in mind.

  • An 'if' can have zero or one else's and it must come after any else if's.
  • An 'if' can have zero to many else if's and they must come before the else.
  • Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax

The following is the syntax of an ‘if...else if...else’ is as follows -

Try the following example program to understand the conditional statements (if- else- if- else statement) in Scala Programming Language.

Example

Save the above program in Demo.scala. The following commands can be used to compile and execute this program.

Command

Output

Nested if-else Statement

It is always legal to use the nest if-else statements, which means that you can use one if or else-if statement inside another if or else-if statement.

Syntax

The syntax for a nested if-else is as follows

Try the below example program to understand the conditional statements (nested- if statement) in Scala Programming Language.

Example

Save the above program in the Demo.scala. The following commands can be used to compile and execute this program.

Command

Output

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Scala Topics