Scala 字面量
详解 Scala 整型、浮点型、布尔、符号、字符、普通与多行字符串(含 stripMargin)、Null 与 Unit 字面量的写法、类型推断及版本演进注意事项。
学完这一章,你能够
- 详解 Scala 整型、浮点型、布尔、符号、字符、普通与多行字符串(含 stripMargin)、Null 与 Unit 字面量的写法、类型推断及版本演进注意事项。
数值与布尔字面量
字面量(Literals)是在源码中直接书写固定值的表达式。整型字面量默认推断为 `Int`,添加 `L` 或 `l` 后缀(推荐大写 `L` 以免与数字 `1` 混淆)则表示 `Long`。整型支持十进制(如 `42`、`0`、`-99`)与 `0x`/`0X` 开头的十六进制(如 `0x2A`、`0XFF`);需注意前导 `0` 开头的八进制字面量自 Scala 2.10 起已正式移除,书写前导零会触发编译报错。
浮点字面量默认推断为双精度 `Double`(如 `3.14`、`-0.001`、`1.0e-10`),仅在末尾显式附加 `f` 或 `F` 后缀时才表示为单精度 `Float`(如 `3.14f`、`-0.001F`)。布尔字面量仅包含 `true` 与 `false` 两个值。
符号、字符与多行字符串字面量
历史 Scala 2 代码中可见以单引号加标识符书写的符号字面量(如 `'x`,等价于 `scala.Symbol("x")`,对应 `scala.Symbol` 驻留实例,但该简写自 Scala 2.13 起已弃用并在 Scala 3 移除,新代码应直接使用 `Symbol("x")` 或枚举/字符串)。字符字面量使用单引号包裹单个字符,例如 `'a'`、Unicode 转义 `'\u0041'` 或控制转义 `'\n'`、`'\t'`。
普通字符串以双引号包裹(如 `"Hello, World!"`),支持标准转义序列;多行原始字符串以三重双引号 `""" ... """` 定界,可直接跨行并保留内部引号与反斜杠。工程中常配合每行前导竖线 `|` 与 `.stripMargin` 方法去除源码缩进空白,输出整齐的多行文本。
Null、Unit 特殊字面量与综合输出
`null` 是 `scala.Null` 类型的唯一字面量,可赋给任意继承自 `AnyRef` 的引用类型(如 `val nullValue: String = null`),但与 `Int`、`Double` 等值类型不兼容(且现代 Scala 推荐用 `Option` 替代裸 `null`)。`Unit` 类型只有一个字面量值 `()`,表达无具体返回结果的副作用操作。
在综合字面量示例 `LiteralsExample` 中,十六进制 `0x2A` 与十进制 `42` 打印结果一致,多行字符串经 `.stripMargin` 裁剪后逐行对齐输出,`null` 打印为 `null`,而 `Unit` 值打印为 `()`。
离线校验 Scala 数值进制、浮点后缀、stripMargin 与 Null/Unit 字面量
展开查看收起
"""Offline Scala semantic verification lab for Chapter 06 (literals)."""
import json
import re
VERSION = "CPython 3.12.14 offline Scala 2.13/3 semantic verifier (scalac absent)"
def case_integer_hex_and_octal_removal():
def parse_scala_int_literal(lit):
s = lit.strip()
is_long = s.endswith(("L", "l"))
body = s[:-1] if is_long else s
if re.fullmatch(r"-?0[xX][0-9a-fA-F]+", body):
return ("Long" if is_long else "Int", int(body, 16))
if re.fullmatch(r"-?0[0-9]+", body):
return ("Error", "octal_removed_since_2_10")
if re.fullmatch(r"-?(0|[1-9][0-9]*)", body):
return ("Long" if is_long else "Int", int(body, 10))
return ("Error", "invalid")
expected = {
"decimal": ("Int", 42),
"negative": ("Int", -99),
"hex": ("Int", 42),
"hex_ff": ("Int", 255),
"long_lit": ("Long", 10000000000),
"octal_rejected": ("Error", "octal_removed_since_2_10"),
}
actual = {
"decimal": parse_scala_int_literal("42"),
"negative": parse_scala_int_literal("-99"),
"hex": parse_scala_int_literal("0x2A"),
"hex_ff": parse_scala_int_literal("0XFF"),
"long_lit": parse_scala_int_literal("10000000000L"),
"octal_rejected": parse_scala_int_literal("077"),
}
return {
"name": "integer_hex_and_octal_removal",
"summary": "校验十进制、十六进制、Long 后缀字面量及 Scala 2.10+ 移除八进制字面量的规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_float_double_and_boolean_literals():
def classify_float(lit):
if lit.endswith(("f", "F")):
return ("Float", float(lit[:-1]))
return ("Double", float(lit))
expected = {
"pi_double": ("Double", 3.14),
"sci_double": ("Double", 1e-10),
"pi_float": ("Float", 3.14),
"neg_float": ("Float", -0.001),
"bool_pair": [True, False],
}
actual = {
"pi_double": classify_float("3.14"),
"sci_double": classify_float("1.0e-10"),
"pi_float": classify_float("3.14f"),
"neg_float": classify_float("-0.001F"),
"bool_pair": [True, False],
}
return {
"name": "float_double_and_boolean_literals",
"summary": "校验 Double 默认推断、f/F 后缀 Float 字面量与 true/false 布尔字面量",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_char_symbol_and_multiline_strip_margin():
def strip_margin(text, margin_char="|"):
lines = text.splitlines()
result = []
for line in lines:
stripped = line.lstrip(" \t")
if stripped.startswith(margin_char):
result.append(stripped[1:])
else:
result.append(line)
return "\n".join(result)
raw_multi = "This is\n |a multi-line\n |string"
cleaned = strip_margin(raw_multi)
symbol_repr = "'" + "x"
expected = {
"unicode_char": "A",
"symbol_to_string": "'x",
"multiline_lines": ["This is", "a multi-line", "string"],
}
actual = {
"unicode_char": "\u0041",
"symbol_to_string": symbol_repr,
"multiline_lines": cleaned.splitlines(),
}
return {
"name": "char_symbol_and_multiline_strip_margin",
"summary": "验证 Unicode 字符字面量、Symbol 字符串表示与多行字符串 stripMargin 对齐裁剪",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_null_and_unit_special_literals():
any_ref_types = {"String", "List", "Object"}
any_val_types = {"Int", "Double", "Boolean", "Char", "Unit"}
expected = {
"null_assignable_to_string": True,
"null_assignable_to_int": False,
"unit_singleton_value": "()",
}
actual = {
"null_assignable_to_string": "String" in any_ref_types,
"null_assignable_to_int": "Int" in any_ref_types and "Int" not in any_val_types,
"unit_singleton_value": "()",
}
return {
"name": "null_and_unit_special_literals",
"summary": "校验 null 仅兼容引用类型(AnyRef)而不兼容值类型(AnyVal)及 Unit 字面量 ()",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_integer_hex_and_octal_removal(),
case_float_double_and_boolean_literals(),
case_char_symbol_and_multiline_strip_margin(),
case_null_and_unit_special_literals(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
它会逐行移除每行开头直到默认分隔符 `|`(含 `|` 本身)之间的缩进空白,使代码排版缩进不会混入最终字符串内容中。