Scala IF...ELSE Statements
Scala IF...ELSE statements determine the code block to be executed based on the result (True or False) of one or more statements.
You can briefly understand the execution process of conditional statements through the following diagram:
if statement
The if statement consists of a boolean expression followed by a statement block.
Syntax
The syntax of the if statement is as follows:
if(布尔表达式)
{
// 如果布尔表达式为 true 则执行该语句块
}
If the boolean expression is true, the statement block inside the braces is executed; otherwise, skip the statement block inside the braces and execute the statement block after the braces.
Example
Example
def main(args: Array[String]) {
var x = 10;
if( x < 20 ){
println("x < 20");
}
}
}
Run example »
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test x < 20
if...else statement
The if statement can be followed by an else statement. The statement block inside else can be executed when the boolean expression is false.
Syntax
The syntax of if...else is as follows:
if(布尔表达式){
// 如果布尔表达式为 true 则执行该语句块
}else{
// 如果布尔表达式为 false 则执行该语句块
}
Example
Example
def main(args: Array[String]) {
var x = 30;
if( x < 20 ){
println("x is less than 20");
}else{
println("x is greater than or equal to 20");
}
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test x 大于等于 20
if...else if...else statement
The if statement can be followed by an else if...else statement, which is useful when there are multiple conditional judgment statements.
Syntax
The syntax of if...else if...else is as follows:
if(布尔表达式 1){
// 如果布尔表达式 1 为 true 则执行该语句块
}else if(布尔表达式 2){
// 如果布尔表达式 2 为 true 则执行该语句块
}else if(布尔表达式 3){
// 如果布尔表达式 3 为 true 则执行该语句块
}else {
// 如果以上条件都为 false 执行该语句块
}
Example
Example
def main(args: Array[String]) {
var x = 30;
if( x == 10 ){
println("The value of X is 10");
}else if( x == 20 ){
println("The value of X is 20");
}else if( x == 30 ){
println("The value of X is 30");
}else{
println("Unable to determine the value of X");
}
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test X 的值为 30
if...else nested statements
if...else nested statements allow one or more if statements to be embedded within an if statement.
Syntax
The syntax of nested if...else statements is as follows:
if(布尔表达式 1){
// 如果布尔表达式 1 为 true 则执行该语句块
if(布尔表达式 2){
// 如果布尔表达式 2 为 true 则执行该语句块
}
}
Nested else if...else statements are similar to nested if...else statements.
Example
Example
def main(args: Array[String]) {
var x = 30;
var y = 10;
if( x == 30 ){
if( y == 10 ){
println("X = 30 , Y = 10");
}
}
}
}
Executing the above code produces the following output:
$ scalac Test.scala $ scala Test X = 30 , Y = 10Other Extensions