The best Scala IF ... ELSE statement Tutorial In 2024, In this tutorial you can learn if statement,if ... else statement,if ... else if ... else statement,if ... else statement nested,
Scala IF /en. ELSE statement block of code is determined by the results of one or more statements of (True or False).
The following figure can be a simple understanding of the execution of the conditional statement:
if there is a block of statements and statements following Boolean expressions.
Syntax if the statement is as follows:
if(布尔表达式) { // 如果布尔表达式为 true 则执行该语句块 }
If the Boolean expression is true then execute a block of statements inside the curly braces, otherwise skip a block of statements inside the curly braces, the statement is executed after the block braces.
object Test { def main(args: Array[String]) { var x = 10; if( x < 20 ){ println("x < 20"); } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test x < 20
After the if statement can be followed by else statements, statements can be executed within the block else to false when the Boolean expression.
if /en. else syntax is as follows:
if(布尔表达式){ // 如果布尔表达式为 true 则执行该语句块 }else{ // 如果布尔表达式为 false 则执行该语句块 }
object Test { def main(args: Array[String]) { var x = 30; if( x < 20 ){ println("x 小于 20"); }else{ println("x 大于 20"); } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test x 大于 20
After the if statement can be followed else if /en. else statement, in the case of multiple conditional statements useful.
if /en. else if /en. else syntax is as follows:
if(布尔表达式 1){ // 如果布尔表达式 1 为 true 则执行该语句块 }else if(布尔表达式 2){ // 如果布尔表达式 2 为 true 则执行该语句块 }else if(布尔表达式 3){ // 如果布尔表达式 3 为 true 则执行该语句块 }else { // 如果以上条件都为 false 执行该语句块 }
object Test { def main(args: Array[String]) { var x = 30; if( x == 10 ){ println("X 的值为 10"); }else if( x == 20 ){ println("X 的值为 20"); }else if( x == 30 ){ println("X 的值为 30"); }else{ println("无法判断 X 的值"); } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test X 的值为 30
Nested if /en. else statements can be embedded in one or more of if statements within the if statement.
Nested if /en. else statement syntax is as follows:
if(布尔表达式 1){ // 如果布尔表达式 1 为 true 则执行该语句块 if(布尔表达式 2){ // 如果布尔表达式 2 为 true 则执行该语句块 } }
else if /en. else statement nested similar nested if /en. else statement.
object Test { def main(args: Array[String]) { var x = 30; var y = 10; if( x == 30 ){ if( y == 10 ){ println("X = 30 , Y = 10"); } } } }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test X = 30 , Y = 10