Kotlin 值类
核对 Kotlin @JvmInline value class 的演进(从 1.3 inline class 到 1.5 稳定)、主构造器单 val 属性、init 校验与私有构造工厂模式、与 data class 差异、语言限制以及装箱/不装箱时机。
学完这一章,你能够
- 核对 Kotlin @JvmInline value class 的演进(从 1.3 inline class 到 1.5 稳定)、主构造器单 val 属性、init 校验与私有构造工厂模式、与 data class 差异、语言限制以及装箱/不装箱时机。
值类定位、版本演进与基本定义
当业务接口同时接收多个 `String` 或 `Int` 参数(如 `fromAccount`、`toAccount`、密码、用户 ID)时,参数顺序传反往往能通过编译而在运行时酿成事故。**值类(Value Class)**为底层基础值包上一层独立语义类型,同时由编译器在绝大多数场景下直接擦除为底层值本身,实现近乎零运行时对象分配开销。该特性最初于 Kotlin 1.3 以 `inline class` 推出,自 Kotlin 1.5 起正式更名并稳定为 `@JvmInline value class`(`@JvmInline` 来自默认导入的 `kotlin.jvm` 包;Kotlin 2.2 中旧 `inline class` 写法会触发弃用警告)。
定义值类时主构造器必须有且仅有**一个 `val` 底层属性**(underlying property),如 `@JvmInline value class UserId(val value: Int)` 与 `Email(val address: String)`。不同值类在编译期互不兼容,传错参数顺序会立刻报错;编译器还会自动为其生成 `equals()`、`hashCode()` 与 `toString()`(格式同数据类,如 `UserId(value=1001)`)。
init 块校验、私有工厂、限制与数据类对比
自 Kotlin 1.4.30 起,值类支持在类体内编写 `init` 块执行不变式校验(例如 `Percentage` 用 `require(value in 0..100)` 在构造阶段拦截 `120`),使类型不仅保证“语义正确”也保证“取值合法”。若还需统一做字符串清洗(如 `trim().lowercase()`),可将主构造器标记为 `private constructor`,并通过伴生对象工厂函数 `Email.of(raw)` 强制外部走统一校验入口。
与关注多字段聚合的 `data class` 不同,值类专注于单值领域封装:值类只能拥有一个 `val` 底层属性,不能声明带幕后字段的额外属性(但可定义纯计算属性,如 `Temperature.fahrenheit`),不能为 `data`/`open`/`abstract`/`sealed`/`inner`,不能继承其他类(但可以实现接口),且不会生成 `copy()` 与 `componentN()`。
装箱与不装箱时机及常见问题
值类的“免分配”前提是编译器能直接按底层类型传递:作为具体类型变量、形参或返回值(如 `fun half(m: Meter): Meter`)时**不装箱**;但一旦被当作 `Any`、所实现的接口(如 `fun show(d: Displayable)`)、可空类型(`UserId?`)、泛型实参(`List<UserId>`)或存入对象数组(`Array<UserId>`),编译器会自动**装箱**为包装对象,且禁止对值类使用引用相等运算符 `===`(编译报错)。由于值类生成了基于底层值的 `equals`/`hashCode`,可直接作为 `Map` 的键,但不支持 `val (v) = UserId(1)` 解构;若需验证具体字节码是否装箱,可通过 `javap` 反编译确认。本站离线校验器已逐项核对上述规则。
值类语法版本演进
| 版本 | 写法 | 说明 |
| Kotlin 1.3 起 | inline class UserId(val value: Int) | 早期实验写法,无需注解,现已弃用 |
| Kotlin 1.5 起 | @JvmInline value class UserId(val value: Int) | 官方稳定写法,JVM 平台必须配合 @JvmInline |
值类(value class)与数据类(data class)对比
| 对比项 | 值类 value class | 数据类 data class |
| 属性数量 | 主构造器有且仅有 1 个 val 属性 | 主构造器至少 1 个属性,可包含多个 |
| 运行时表示 | 具体类型场景退化为底层值,避免对象分配 | 始终作为普通堆对象分配 |
| 自动生成成员 | equals / hashCode / toString | equals / hashCode / toString / copy / componentN |
| 解构声明 | 不支持(无 componentN) | 支持,按主构造器属性顺序解构 |
| 继承 | 不能继承类,可以实现接口 | 默认 final,不能为 open/abstract/sealed,可实现接口 |
| 典型用途 | 领域 ID、单位、金额、百分比等单值封装 | DTO、多字段聚合、函数多值返回 |
值类语言结构限制
| 限制 | 说明 |
| 主构造器有且仅有一个 val 参数 | 多于一个参数将无法映射为单一底层表示 |
| 底层属性必须为只读 val | 值类语义不可原地修改底层存储 |
| 禁止声明额外带幕后字段的属性 | 仅允许编写无状态的自定义 getter 计算属性 |
| 禁止声明为 inner 内部类 | 内部类需隐式持有外部类引用,与零开销单值表示冲突 |
| 不能继承其他类 | 但允许实现接口 |
| 必须是 final | 禁止与 open、abstract、sealed、data 组合 |
| JVM 平台必须标注 @JvmInline | 原生后端(如 Kotlin/Native)无需该注解 |
值类装箱与不装箱时机矩阵
| 使用方式 | 是否装箱 | 原因 |
| 作为具体类型的变量、参数或返回值 | 不装箱 | 编译后直接使用底层原始类型传递 |
| 赋给 Any 或实现的接口类型 | 装箱 | 多态分发需要对象头与虚方法表 |
| 用作可空类型 UserId? | 装箱 | 原始基本类型无法表达 null 状态 |
| 作为泛型实参(如 List<UserId>) | 装箱 | JVM 泛型类型实参仅接受引用类型 |
| 存入对象数组 Array<UserId> | 装箱 | 引用类型数组元素存储对象引用 |
| 使用 === 做引用身份比较 | 编译报错 | 值类不存在稳定对象引用身份 |
运行离线 Python 校验:Kotlin 值类类型安全、init/工厂校验、结构约束与装箱矩阵
展开查看收起
"""Offline Kotlin 2.x semantic verifier for Chapter 28: Value Classes."""
from dataclasses import dataclass
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
@dataclass(frozen=True)
class UserId:
value: int
def __str__(self) -> str:
return f"UserId(value={self.value})"
@dataclass(frozen=True)
class Email:
address: str
@classmethod
def of(cls, raw: str) -> "Email":
normalized = raw.strip().lower()
if "@" not in normalized:
raise ValueError(f"邮箱格式不正确:{raw}")
return cls(normalized)
def __str__(self) -> str:
return f"Email(address={self.address})"
def case_type_safety_and_generated_members():
def send_mail(to: Email, user_id: UserId) -> str:
if not isinstance(to, Email) or not isinstance(user_id, UserId):
raise TypeError("COMPILE_ERROR: Type mismatch for value class parameters")
return f"向 {to.address} 的用户 {user_id.value} 发送邮件"
email = Email("dev@mbsky.cn")
uid = UserId(1001)
swapped_rejected = False
try:
send_mail(uid, email) # type: ignore[arg-type]
except TypeError:
swapped_rejected = True
lookup = {UserId(1001): "Alice"}
actual = {
"mail_msg": send_mail(email, uid),
"swapped_rejected": swapped_rejected,
"eq_same": uid == UserId(1001),
"eq_diff": UserId(1001) == UserId(1002),
"to_string": str(uid),
"map_key_lookup": lookup[UserId(1001)],
"supports_componentN_destructuring": False,
}
expected = {
"mail_msg": "向 dev@mbsky.cn 的用户 1001 发送邮件",
"swapped_rejected": True,
"eq_same": True,
"eq_diff": False,
"to_string": "UserId(value=1001)",
"map_key_lookup": "Alice",
"supports_componentN_destructuring": False,
}
return {
"name": "type_safety_and_generated_members",
"summary": "Verify nominal type safety, equals/hashCode/toString generation, Map keys, and no destructuring",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_init_validation_and_private_factory():
def make_percentage(v: int) -> int:
if not (0 <= v <= 100):
raise ValueError(f"百分比必须在 0 到 100 之间,当前为 {v}")
return v
ok_pct = make_percentage(80)
bad_pct_msg = None
try:
make_percentage(120)
except ValueError as exc:
bad_pct_msg = str(exc)
clean_email = Email.of(" DEV@Mbsky.CN ")
bad_email_msg = None
try:
Email.of("invalid-domain.cn")
except ValueError as exc:
bad_email_msg = str(exc)
actual = {
"ok_pct": ok_pct,
"bad_pct_msg": bad_pct_msg,
"clean_email": clean_email.address,
"bad_email_msg": bad_email_msg,
}
expected = {
"ok_pct": 80,
"bad_pct_msg": "百分比必须在 0 到 100 之间,当前为 120",
"clean_email": "dev@mbsky.cn",
"bad_email_msg": "邮箱格式不正确:invalid-domain.cn",
}
return {
"name": "init_validation_and_private_factory",
"summary": "Verify value class init block validation and private constructor + companion factory normalization",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_computed_property_and_restrictions():
class Temperature:
def __init__(self, celsius: float):
self.celsius = celsius
@property
def fahrenheit(self) -> float:
return self.celsius * 9.0 / 5.0 + 32.0
def validate_value_class(spec: dict) -> list[str]:
errs = []
if spec["param_count"] != 1 or not spec["param_is_val"]:
errs.append("must_have_single_val_param")
if spec["has_extra_backing_field"]:
errs.append("no_extra_backing_field")
if spec["modifiers"] & {"data", "open", "abstract", "sealed", "inner"}:
errs.append("forbidden_modifier")
if spec["extends_class"]:
errs.append("cannot_extend_class")
if spec["target_jvm"] and not spec["has_jvm_inline"]:
errs.append("missing_JvmInline")
return errs
t = Temperature(25.0)
valid_spec = {
"param_count": 1,
"param_is_val": True,
"has_extra_backing_field": False,
"modifiers": set(),
"extends_class": False,
"target_jvm": True,
"has_jvm_inline": True,
}
invalid_spec = {
"param_count": 2,
"param_is_val": False,
"has_extra_backing_field": True,
"modifiers": {"data", "open"},
"extends_class": True,
"target_jvm": True,
"has_jvm_inline": False,
}
actual = {
"celsius": t.celsius,
"fahrenheit": t.fahrenheit,
"valid_errors": validate_value_class(valid_spec),
"invalid_errors": validate_value_class(invalid_spec),
}
expected = {
"celsius": 25.0,
"fahrenheit": 77.0,
"valid_errors": [],
"invalid_errors": [
"must_have_single_val_param",
"no_extra_backing_field",
"forbidden_modifier",
"cannot_extend_class",
"missing_JvmInline",
],
}
return {
"name": "computed_property_and_restrictions",
"summary": "Verify backing-field-free computed property and Kotlin @JvmInline value class structural rules",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_boxing_vs_unboxed_rules():
def boxing_behavior(usage: str) -> str:
rules = {
"concrete_type": "unboxed",
"any_or_interface": "boxed",
"nullable_UserId?": "boxed",
"generic_List<UserId>": "boxed",
"array_Array<UserId>": "boxed",
"referential_eq_===": "compile_error",
}
return rules[usage]
m_val = 10.0
half_val = m_val / 2.0
shown = f"{m_val} m"
actual = {
"half_meter": half_val,
"displayable_show": shown,
"boxing_matrix": {k: boxing_behavior(k) for k in [
"concrete_type",
"any_or_interface",
"nullable_UserId?",
"generic_List<UserId>",
"array_Array<UserId>",
"referential_eq_===",
]},
}
expected = {
"half_meter": 5.0,
"displayable_show": "10.0 m",
"boxing_matrix": {
"concrete_type": "unboxed",
"any_or_interface": "boxed",
"nullable_UserId?": "boxed",
"generic_List<UserId>": "boxed",
"array_Array<UserId>": "boxed",
"referential_eq_===": "compile_error",
},
}
return {
"name": "boxing_vs_unboxed_rules",
"summary": "Verify concrete unboxed passing vs interface/nullable/generic/array boxing and === prohibition",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_type_safety_and_generated_members(),
case_init_validation_and_private_factory(),
case_computed_property_and_restrictions(),
case_boxing_vs_unboxed_rules(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
当值类被当作接口或 Any、可空类型(如 UserId?)、泛型实参(如 List<UserId>)或 Array<UserId> 元素使用时都会装箱;因为值类在未装箱时没有对象身份且装箱后可能生成不同包装实例,语言直接禁止对其使用 ===。