"""Offline Kotlin 2.x semantic verifier for Chapter 23: Sealed Classes & Interfaces."""
from dataclasses import dataclass
import json
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class SealedBase:
"""Emulates Kotlin sealed class abstract & protected constructor constraint."""
def __init__(self):
if type(self) is SealedBase:
raise TypeError("Sealed types cannot be instantiated directly")
@dataclass(frozen=True)
class Success(SealedBase):
data: str
def __str__(self) -> str:
return f"Success(data={self.data})"
@dataclass(frozen=True)
class Failure(SealedBase):
message: str
class _Loading(SealedBase):
def __str__(self) -> str:
return "Loading"
Loading = _Loading()
def check_subclass_placement(kotlin_ver: tuple[int, int], nested: bool, same_file: bool, same_pkg_mod: bool) -> bool:
if kotlin_ver < (1, 1):
return nested
if kotlin_ver < (1, 5):
return same_file
return same_pkg_mod
def case_sealed_hierarchy_and_placement():
direct_blocked = False
try:
SealedBase()
except TypeError:
direct_blocked = True
res = Success("mbsky.cn")
placement = {
"k1_0_top_level_same_file": check_subclass_placement((1, 0), False, True, True),
"k1_0_nested": check_subclass_placement((1, 0), True, True, True),
"k1_1_same_file": check_subclass_placement((1, 1), False, True, True),
"k1_1_other_file_same_pkg": check_subclass_placement((1, 1), False, False, True),
"k1_5_other_file_same_pkg": check_subclass_placement((1, 5), False, False, True),
"k1_5_other_module": check_subclass_placement((1, 5), False, False, False),
}
actual = {
"direct_instantiation_blocked": direct_blocked,
"success_str": str(res),
"loading_singleton": Loading is Loading,
"placement": placement,
}
expected = {
"direct_instantiation_blocked": True,
"success_str": "Success(data=mbsky.cn)",
"loading_singleton": True,
"placement": {
"k1_0_top_level_same_file": False,
"k1_0_nested": True,
"k1_1_same_file": True,
"k1_1_other_file_same_pkg": False,
"k1_5_other_file_same_pkg": True,
"k1_5_other_module": False,
},
}
return {
"name": "sealed_hierarchy_and_placement",
"summary": "Verify abstract sealed constructor guard and Kotlin 1.0/1.1/1.5 subclass placement rules",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sealed_interface_and_multi_impl():
class AppEvent:
pass
@dataclass(frozen=True)
class Click(AppEvent):
x: int
y: int
@dataclass(frozen=True)
class Scroll(AppEvent):
delta: int
class _Refresh(AppEvent):
def __str__(self) -> str:
return "Refresh"
Refresh = _Refresh()
def handle(event: AppEvent) -> str:
if isinstance(event, Click):
return f"点击坐标:({event.x}, {event.y})"
if isinstance(event, Scroll):
return f"滚动:{event.delta}"
if event is Refresh:
return "刷新"
raise AssertionError("Non-exhaustive")
class Clickable:
pass
class Hoverable:
pass
class ActionButton(Clickable, Hoverable):
pass
btn = ActionButton()
actual = {
"handled": [handle(Click(10, 20)), handle(Scroll(-5)), handle(Refresh)],
"is_clickable": isinstance(btn, Clickable),
"is_hoverable": isinstance(btn, Hoverable),
}
expected = {
"handled": ["点击坐标:(10, 20)", "滚动:-5", "刷新"],
"is_clickable": True,
"is_hoverable": True,
}
return {
"name": "sealed_interface_and_multi_impl",
"summary": "Verify sealed interface event dispatch and multiple sealed interface implementation",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_exhaustive_when_checker():
sealed_subtypes = {"Idle", "Running", "Error"}
def verify_when(covered: set[str], has_else: bool, as_expression: bool, kotlin_ver: tuple[int, int]) -> str:
missing = sorted(sealed_subtypes - covered)
if not missing or has_else:
return "OK"
if as_expression or kotlin_ver >= (1, 7):
return f"COMPILE_ERROR: missing {missing}"
if kotlin_ver >= (1, 6):
return f"WARNING: missing {missing}"
return "OK"
def label(state: tuple) -> str:
tag = state[0]
if tag == "Idle":
return "空闲"
if tag == "Running":
return "运行中"
if tag == "Error":
return f"错误码 {state[1]}"
raise ValueError(tag)
actual = {
"labels": [label(("Idle",)), label(("Running",)), label(("Error", 404))],
"full_no_else": verify_when({"Idle", "Running", "Error"}, False, True, (2, 2)),
"missing_expr": verify_when({"Idle", "Running"}, False, True, (2, 2)),
"missing_stmt_1_6": verify_when({"Idle", "Running"}, False, False, (1, 6)),
"missing_stmt_1_7": verify_when({"Idle", "Running"}, False, False, (1, 7)),
}
expected = {
"labels": ["空闲", "运行中", "错误码 404"],
"full_no_else": "OK",
"missing_expr": "COMPILE_ERROR: missing ['Error']",
"missing_stmt_1_6": "WARNING: missing ['Error']",
"missing_stmt_1_7": "COMPILE_ERROR: missing ['Error']",
}
return {
"name": "exhaustive_when_checker",
"summary": "Verify exhaustive when on sealed hierarchies for expressions and Kotlin 1.6/1.7+ statements",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_sealed_vs_enum_modeling():
enum_status = {"OK": 200, "NOT_FOUND": 404, "TIMEOUT": 0}
def describe_response(resp: tuple) -> str:
kind = resp[0]
if kind == "Ok":
return f"返回内容:{resp[1]}"
if kind == "NotFound":
return f"找不到路径:{resp[1]}"
if kind == "Timeout":
return "请求超时"
raise ValueError(kind)
actual = {
"enum_ok_code": enum_status["OK"],
"responses": [
describe_response(("Ok", "KOTLIN")),
describe_response(("NotFound", "/missing")),
describe_response(("Timeout",)),
],
}
expected = {
"enum_ok_code": 200,
"responses": ["返回内容:KOTLIN", "找不到路径:/missing", "请求超时"],
}
return {
"name": "sealed_vs_enum_modeling",
"summary": "Compare fixed-schema enum constants against per-branch heterogeneous sealed payloads",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_sealed_hierarchy_and_placement(),
case_sealed_interface_and_multi_impl(),
case_exhaustive_when_checker(),
case_sealed_vs_enum_modeling(),
]
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-sealed-class-lab/explore-sealed-class.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-sealed-class.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM/Gradle 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2166.zip