条件表达式 #
一、if 表达式 #
1.1 基本语法 #
Scala 的 if 是表达式,有返回值:
scala
val result = if (x > 0) "positive" else "non-positive"
1.2 Scala 3 新语法 #
使用 then 和 else 关键字:
scala
val result = if x > 0 then "positive" else "non-positive"
val message = if score >= 60 then
"pass"
else
"fail"
1.3 传统语法 #
scala
val result = if (x > 0) "positive" else "non-positive"
val message = if (score >= 60) {
"pass"
} else {
"fail"
}
二、if-else 链 #
2.1 多条件判断 #
scala
val grade = if score >= 90 then "A"
else if score >= 80 then "B"
else if score >= 70 then "C"
else if score >= 60 then "D"
else "F"
2.2 嵌套 if #
scala
val result = if x > 0 then
if x > 100 then "large positive"
else "small positive"
else
if x < -100 then "large negative"
else "small negative"
三、块表达式 #
3.1 代码块作为表达式 #
代码块的值是最后一个表达式的值:
scala
val result = {
val x = 10
val y = 20
x + y
}
println(result)
3.2 if 块表达式 #
scala
val message = if score >= 60 then
val grade = "pass"
val msg = s"Congratulations! You got a $grade"
msg
else
"Try again!"
3.3 多语句块 #
scala
val result = if condition then
println("Processing...")
val temp = compute()
temp * 2
else
0
四、三元运算符替代 #
4.1 Java 三元运算符 #
java
String result = x > 0 ? "positive" : "non-positive";
4.2 Scala if 表达式 #
scala
val result = if x > 0 then "positive" else "non-positive"
Scala 没有 ?: 运算符,因为 if 表达式已经足够简洁。
五、返回值类型 #
5.1 相同类型分支 #
scala
val result: String = if x > 0 then "positive" else "negative"
5.2 不同类型分支 #
返回公共超类型:
scala
val result: Any = if condition then 42 else "not a number"
5.3 Unit 返回类型 #
scala
if condition then
println("true")
else
println("false")
5.4 省略 else #
没有 else 分支时返回 Unit:
scala
val result: Unit = if x > 0 then println("positive")
六、条件表达式最佳实践 #
6.1 保持简洁 #
scala
val status = if score >= 60 then "pass" else "fail"
val discount = if isMember then 0.1 else 0.0
6.2 避免嵌套过深 #
scala
val category = age match
case a if a < 13 => "child"
case a if a < 20 => "teenager"
case a if a < 65 => "adult"
case _ => "senior"
6.3 使用块表达式处理复杂逻辑 #
scala
val result = if condition then
val temp = compute()
val processed = transform(temp)
processed
else
defaultValue
七、条件表达式与模式匹配对比 #
7.1 使用 if-else #
scala
val grade = if score >= 90 then "A"
else if score >= 80 then "B"
else if score >= 70 then "C"
else if score >= 60 then "D"
else "F"
7.2 使用模式匹配 #
scala
val grade = score match
case s if s >= 90 => "A"
case s if s >= 80 => "B"
case s if s >= 70 => "C"
case s if s >= 60 => "D"
case _ => "F"
八、实用示例 #
8.1 输入验证 #
scala
def validateAge(age: Int): Either[String, Int] =
if age < 0 then Left("Age cannot be negative")
else if age > 150 then Left("Age seems invalid")
else Right(age)
8.2 默认值处理 #
scala
def getValue(opt: Option[String]): String =
if opt.isDefined then opt.get else "default"
def getValue2(opt: Option[String]): String =
opt.getOrElse("default")
8.3 条件计算 #
scala
def calculate(price: Double, quantity: Int, isMember: Boolean): Double =
val subtotal = price * quantity
val discount = if isMember && subtotal > 100 then 0.1 else 0.0
subtotal * (1 - discount)
8.4 状态判断 #
scala
def getStatus(score: Int): String =
if score >= 90 then "Excellent"
else if score >= 70 then "Good"
else if score >= 60 then "Pass"
else "Fail"
九、Scala 2 与 Scala 3 语法对比 #
9.1 if 语法 #
Scala 2:
scala
if (x > 0) {
"positive"
} else {
"non-positive"
}
Scala 3:
scala
if x > 0 then
"positive"
else
"non-positive"
9.2 混合使用 #
Scala 3 仍然支持传统语法:
scala
val result = if (x > 0) "positive" else "non-positive"
val result2 = if x > 0 then "positive" else "non-positive"
十、常见陷阱 #
10.1 忘记 else 分支 #
scala
val result = if condition then "yes"
println(result)
10.2 类型不匹配 #
scala
val result = if condition then 42 else "not a number"
val num: Int = result
10.3 副作用与返回值混淆 #
scala
val result = if condition then
println("yes")
"yes"
else
println("no")
"no"
十一、总结 #
if 表达式特点 #
| 特性 | 说明 |
|---|---|
| 返回值 | 有返回值,是表达式 |
| 类型推断 | 返回公共超类型 |
| else 可选 | 没有 else 返回 Unit |
| Scala 3 | 支持 then 关键字 |
最佳实践 #
- 利用 if 表达式的返回值
- 保持条件表达式简洁
- 复杂逻辑使用块表达式
- 多条件考虑使用模式匹配
下一步,让我们学习 模式匹配!
最后更新:2026-03-27