Understanding Scala if, if...else, and Nested Conditional Statements
This article explains Scala's conditional constructs—including simple if statements, if‑else, if‑else‑if chains, and nested if‑else structures—by describing their syntax, providing clear code examples, and showing the corresponding command‑line compilation and execution results.
if Statement
In Scala, an if statement consists of a Boolean expression followed by a block of code that is executed when the expression evaluates to true.
Syntax
if (BooleanExpression) {
// code executed when the expression is true
}Example
object Test {
def main(args: Array[String]) {
var x = 10;
if (x < 20) {
println("x < 20")
}
}
}Running the code produces:
$ scalac Test.scala
$ scala Test
x < 20if...else Statement
An if statement can be followed by an else block, which is executed when the Boolean expression is false.
Syntax
if (BooleanExpression) {
// code executed when true
} else {
// code executed when false
}Example
object Test {
def main(args: Array[String]) {
var x = 30;
if (x < 20) {
println("x 小于 20")
} else {
println("x 大于 20")
}
}
}Running the code produces:
$ scalac Test.scala
$ scala Test
x 大于 20if...else if...else Statement
Multiple conditions can be chained using else if, allowing the program to select the first true condition among several.
Syntax
if (BooleanExpression1) {
// code for true condition 1
} else if (BooleanExpression2) {
// code for true condition 2
} else if (BooleanExpression3) {
// code for true condition 3
} else {
// code when all conditions are false
}Example
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 的值")
}
}
}Running the code produces:
$ scalac Test.scala
$ scala Test
X 的值为 30Nested if...else Statements
Conditional statements can be nested, allowing an if block to contain another if statement.
Syntax
if (BooleanExpression1) {
// code for true condition 1
if (BooleanExpression2) {
// code for true condition 2
}
}Example
object Test {
def main(args: Array[String]) {
var x = 30;
var y = 10;
if (x == 30) {
if (y == 10) {
println("X = 30 , Y = 10")
}
}
}
}Running the code produces:
$ scalac Test.scala
$ scala Test
X = 30 , Y = 10Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
