"""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()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。
入口文件:projects/kotlin-value-class-lab/explore-value-class.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-value-class.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2173.zip