Scala IF...ELSE 语句
讲解 Scala 单分支 if、双分支 if...else、多分支 else if 与嵌套条件结构,并重点阐明 Scala 中 if/else 作为有返回值表达式的类型推断规则。
学完这一章,你能够
- 讲解 Scala 单分支 if、双分支 if...else、多分支 else if 与嵌套条件结构,并重点阐明 Scala 中 if/else 作为有返回值表达式的类型推断规则。
条件分支执行流程与 if / if...else 结构
条件分支依据一个或多个布尔表达式的求值结果(`true` 或 `false`)选择执行路径。与 Java 仅将 `if` 视作控制语句不同,Scala 的 `if/else` 本身是带返回值的表达式,因此可直接将条件结果赋给 `val`,不再需要单独的三元运算符 `?:`。
单分支 `if (布尔表达式) { ... }` 在条件为 `true` 时执行代码块,否则跳过。例如 `x = 10` 满足 `x < 20`,输出 `x < 20`。需注意省略 `else` 分支时,Scala 相当于在隐式 `else` 中返回 `Unit` 值 `()`,若把无 `else` 的 `if` 当作值赋给变量,推断类型会放宽为两个分支的公共父类型(如 `AnyVal` 或 `Any`)。
双分支 `if (条件) { ... } else { ... }` 覆盖条件为真与为假两种互斥路径:当 `x = 30` 时 `x < 20` 为假,进入 `else` 分支输出 `x 大于等于 20`。若两侧分支返回同一类型(例如均返回 `String`),整个表达式即可精确推断为该类型。
多分支 else if 链与嵌套条件
当存在多个互斥区间或离散取值时,可串联 `if ... else if ... else`。系统按从上到下顺序依次检测条件,命中首个为 `true` 的分支后即结束整个判断链。例如 `x = 30` 依次跳过 `10` 与 `20` 后命中第三个分支,输出 `X 的值为 30`;若所有条件均不成立则落入末尾 `else` 兜底分支。
`if` 或 `else if` 语句块内部还可以嵌套多层 `if` 以表达组合前置条件(如先判定 `x == 30`,再于内部判定 `y == 10` 后输出 `X = 30 , Y = 10`)。在 Scala 3 中还引入了可选缩进语法 `if x < 20 then ... else ...`,但经典圆括号加花括号语法仍完全兼容。
离线校验 Scala 条件分支路径、if 表达式返回值与缺省 else 类型推断
"""Offline Scala semantic verification lab for Chapter 11 (if-else)."""
import json
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_if_else_branch_paths():
def single_if(x):
return "x < 20" if x < 20 else ""
def two_way(x):
return "x 小于 20" if x < 20 else "x 大于等于 20"
expected = {
"single_if_10": "x < 20",
"single_if_25": "",
"two_way_30": "x 大于等于 20",
"two_way_15": "x 小于 20",
}
actual = {
"single_if_10": single_if(10),
"single_if_25": single_if(25),
"two_way_30": two_way(30),
"two_way_15": two_way(15),
}
return {
"name": "if_else_branch_paths",
"summary": "验证单分支 if 与双分支 if...else 在条件真假时的执行路径",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_if_else_if_and_nested_conditions():
def multi_branch(x):
if x == 10:
return "X 的值为 10"
elif x == 20:
return "X 的值为 20"
elif x == 30:
return "X 的值为 30"
else:
return "无法判断 X 的值"
def nested(x, y):
if x == 30:
if y == 10:
return "X = 30 , Y = 10"
return "not matched"
expected = {
"multi_30": "X 的值为 30",
"multi_99": "无法判断 X 的值",
"nested_30_10": "X = 30 , Y = 10",
"nested_30_20": "not matched",
}
actual = {
"multi_30": multi_branch(30),
"multi_99": multi_branch(99),
"nested_30_10": nested(30, 10),
"nested_30_20": nested(30, 20),
}
return {
"name": "if_else_if_and_nested_conditions",
"summary": "验证多分支 else if 链与嵌套 if 语句的顺序求值逻辑",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_if_expression_return_value():
# Scala if/else is an expression replacing Java ternary operator
def max_val(a, b):
return a if a >= b else b
status = "pass" if 85 >= 60 else "fail"
expected = {"max_val": 42, "status": "pass", "inferred_same_type": "Int"}
actual = {"max_val": max_val(17, 42), "status": status, "inferred_same_type": "Int"}
return {
"name": "if_expression_return_value",
"summary": "验证 Scala if/else 作为表达式直接返回值并替代三元运算符的语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_if_without_else_unit_type():
def infer_if_type(then_type, else_type=None):
et = else_type if else_type is not None else "Unit"
if then_type == et:
return then_type
if then_type in ("Int", "Double", "Unit") and et in ("Int", "Double", "Unit"):
return "AnyVal"
return "Any"
expected = {
"int_and_int": "Int",
"int_without_else": "AnyVal",
"string_without_else": "Any",
"unit_without_else": "Unit",
}
actual = {
"int_and_int": infer_if_type("Int", "Int"),
"int_without_else": infer_if_type("Int"),
"string_without_else": infer_if_type("String"),
"unit_without_else": infer_if_type("Unit"),
}
return {
"name": "if_without_else_unit_type",
"summary": "校验省略 else 分支时隐式补全 Unit 值 () 导致的公共父类型推断规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_if_else_branch_paths(),
case_if_else_if_and_nested_conditions(),
case_if_expression_return_value(),
case_if_without_else_unit_type(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在 CPython 3.12.14 离线脚本中验证单分支、双分支、多分支 else if、嵌套 if、if 表达式返回值及缺省 else 推断公共父类型全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
当前源码 SHA256:573f86e34bc6bcf370836020a943581869ce37c995324b8611a5fadc9813021c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Scala 2.13/3 语义验证器(本机未安装 scala/scalac)。
ZIP SHA256:b48144750536060ad986323718fa232c6d2cf835b98f967d0b42f56d5db722c6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Scala 中写 `val r = if (x > 0) 1` 而不写 `else` 分支时,变量 `r` 会被推断成什么类型?为什么?
展开参考解答
会被推断为 `AnyVal`(而非 `Int`),因为缺少 `else` 分支时编译器隐式补全 `else ()`,而 `Int` 与 `Unit` 的最小公共超类型是 `AnyVal`。