蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 data class 五大成员、六项约束、浅拷贝、componentN 解构与 data object

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。explore-data-class.py
explore-data-class.py271 行
"""Offline Kotlin 2.x semantic verifier for Chapter 21 (data-class)."""
import json
import sys
from typing import Any

VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"


class SiteData:
    """Models `data class SiteData(val name: String, val url: String, val age: Int)`."""

    def __init__(self, name: str, url: str, age: int, tags: list[str] | None = None) -> None:
        self._name = name
        self._url = url
        self._age = age
        self.tags = tags if tags is not None else []  # shared reference demonstrates shallow copy

    @property
    def name(self) -> str:
        return self._name

    @property
    def url(self) -> str:
        return self._url

    @property
    def age(self) -> int:
        return self._age

    def component1(self) -> str:
        return self._name

    def component2(self) -> str:
        return self._url

    def component3(self) -> int:
        return self._age

    def __iter__(self):
        yield self.component1()
        yield self.component2()
        yield self.component3()

    def copy(self, *, name: str | None = None, url: str | None = None, age: int | None = None) -> "SiteData":
        return SiteData(
            self._name if name is None else name,
            self._url if url is None else url,
            self._age if age is None else age,
            tags=self.tags,  # shallow copy!
        )

    def __eq__(self, other: object) -> bool:
        return isinstance(other, SiteData) and (self._name, self._url, self._age) == (other._name, other._url, other._age)

    def __hash__(self) -> int:
        return hash((self._name, self._url, self._age))

    def __str__(self) -> str:
        return f"SiteData(name={self._name}, url={self._url}, age={self._age})"


class UserWithBodyProp:
    """Models `data class User(val name: String) { var city: String = '北京' }`."""

    def __init__(self, name: str) -> None:
        self.name = name
        self.city = "北京"  # body property excluded from equals/hashCode/toString/componentN

    def __eq__(self, other: object) -> bool:
        return isinstance(other, UserWithBodyProp) and self.name == other.name

    def __hash__(self) -> int:
        return hash(self.name)

    def __str__(self) -> str:
        return f"User(name={self.name})"


class Point:
    """Ordinary class implementing custom operator component1()/component2()."""

    def __init__(self, x: int, y: int) -> None:
        self.x = x
        self.y = y

    def component1(self) -> int:
        return self.x

    def component2(self) -> int:
        return self.y


class _DataObject:
    """Models Kotlin 1.9+ `data object` with readable toString and singleton equality."""

    def __init__(self, name: str) -> None:
        self._name = name

    def __str__(self) -> str:
        return self._name

    def __eq__(self, other: object) -> bool:
        return self is other

    def __hash__(self) -> int:
        return hash(self._name)


LOADING = _DataObject("Loading")
EMPTY = _DataObject("Empty")


def validate_data_class_decl(primary_params: list[tuple[str, bool]], modifiers: set[str]) -> list[str]:
    errs: list[str] = []
    if len(primary_params) < 1:
        errs.append("must_have_at_least_one_primary_param")
    if any(not is_prop for _, is_prop in primary_params):
        errs.append("all_primary_params_must_be_val_or_var")
    for forbidden in ("abstract", "open", "sealed", "inner"):
        if forbidden in modifiers:
            errs.append(f"cannot_be_{forbidden}")
    return errs


def run_cases() -> list[dict]:
    cases: list[dict] = []

    # Case 1: Generated equals, hashCode, toString, and the 6 data class declaration constraints
    s1 = SiteData("蓝色天空网", "www.mbsky.com", 12, tags=["kotlin"])
    s2 = SiteData("蓝色天空网", "www.mbsky.com", 12, tags=["kotlin"])
    actual_1 = {
        "to_string": str(s1),
        "struct_eq": s1 == s2,
        "hash_eq": hash(s1) == hash(s2),
        "valid_decl_errors": validate_data_class_decl([("id", True)], set()),
        "empty_params_errors": validate_data_class_decl([], set()),
        "non_val_param_errors": validate_data_class_decl([("name", False)], set()),
        "forbidden_mods_errors": validate_data_class_decl([("id", True)], {"abstract", "open", "sealed", "inner"}),
    }
    expected_1 = {
        "to_string": "SiteData(name=蓝色天空网, url=www.mbsky.com, age=12)",
        "struct_eq": True,
        "hash_eq": True,
        "valid_decl_errors": [],
        "empty_params_errors": ["must_have_at_least_one_primary_param"],
        "non_val_param_errors": ["all_primary_params_must_be_val_or_var"],
        "forbidden_mods_errors": ["cannot_be_abstract", "cannot_be_open", "cannot_be_sealed", "cannot_be_inner"],
    }
    cases.append({
        "name": "data_class_generated_members_and_constraints",
        "summary": "Verify data class equals/hashCode/toString and all 6 primary-constructor/modifier requirements.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: copy() partial updates & shallow-copy reference sharing
    s = SiteData("蓝色天空网", "www.mbsky.com", 12, tags=["kotlin"])
    mirror = s.copy(url="m.mbsky.com")
    renamed = s.copy(name="MBSKY 教程", age=13)
    same = s.copy()
    actual_2 = {
        "mirror": str(mirror),
        "renamed": str(renamed),
        "same_eq": same == s,
        "same_ref_eq": same is s,
        "shallow_copy_shares_nested_list": same.tags is s.tags,
    }
    expected_2 = {
        "mirror": "SiteData(name=蓝色天空网, url=m.mbsky.com, age=12)",
        "renamed": "SiteData(name=MBSKY 教程, url=www.mbsky.com, age=13)",
        "same_eq": True,
        "same_ref_eq": False,
        "shallow_copy_shares_nested_list": True,
    }
    cases.append({
        "name": "data_class_copy_and_shallow_semantics",
        "summary": "Verify copy() partial field override, new object identity, and shallow-copy sharing of reference fields.",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: Destructuring (componentN, underscore _, Map, custom Point) & body property exclusion
    name, url, age = s
    _, only_url, _ = s
    p = Point(3, 4)
    px, py = p.component1(), p.component2()
    u1 = UserWithBodyProp("mbsky")
    u2 = UserWithBodyProp("mbsky")
    u1.city = "上海"
    u2.city = "广州"
    actual_3 = {
        "destructured": [name, url, age],
        "underscore_only_url": only_url,
        "custom_component_point": [px, py],
        "body_prop_excluded_from_eq": u1 == u2,
        "body_prop_actually_differs": u1.city == u2.city,
        "body_prop_excluded_from_tostring": str(u1),
    }
    expected_3 = {
        "destructured": ["蓝色天空网", "www.mbsky.com", 12],
        "underscore_only_url": "www.mbsky.com",
        "custom_component_point": [3, 4],
        "body_prop_excluded_from_eq": True,
        "body_prop_actually_differs": False,
        "body_prop_excluded_from_tostring": "User(name=mbsky)",
    }
    cases.append({
        "name": "destructuring_componentN_and_body_exclusion",
        "summary": "Verify componentN destructuring, underscore placeholders, custom componentN, and body property exclusion from equals.",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: Pair, Triple, and Kotlin 1.9+ data object in sealed hierarchy
    pair = ("mbsky", 95)
    pair_copy = (pair[0], 100)
    triple = ("MBSKY", "www.mbsky.com", 2026)

    def describe_state(state: Any) -> str:
        if state == LOADING:
            return "加载中"
        if state == EMPTY:
            return "暂无数据"
        if isinstance(state, tuple) and state[0] == "Success":
            return f"成功:{state[1]}"
        raise AssertionError("unreachable")

    actual_4 = {
        "pair_fields": [pair[0], pair[1]],
        "pair_copy": list(pair_copy),
        "triple_destructured": list(triple),
        "data_object_tostring": [str(LOADING), str(EMPTY)],
        "data_object_singleton_eq": LOADING == LOADING,
        "sealed_when_states": [
            describe_state(LOADING),
            describe_state(EMPTY),
            describe_state(("Success", "www.mbsky.com")),
        ],
        "data_object_since": "1.9",
    }
    expected_4 = {
        "pair_fields": ["mbsky", 95],
        "pair_copy": ["mbsky", 100],
        "triple_destructured": ["MBSKY", "www.mbsky.com", 2026],
        "data_object_tostring": ["Loading", "Empty"],
        "data_object_singleton_eq": True,
        "sealed_when_states": ["加载中", "暂无数据", "成功:www.mbsky.com"],
        "data_object_since": "1.9",
    }
    cases.append({
        "name": "pair_triple_and_data_object_1_9",
        "summary": "Verify Pair/Triple destructuring & copy, plus Kotlin 1.9+ data object toString and sealed state usage.",
        "expected": expected_4,
        "actual": actual_4,
        "passed": actual_4 == expected_4,
    })

    return cases


def main() -> None:
    payload = {"version": VERSION, "cases": run_cases()}
    sys.stdout.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。

入口文件:projects/kotlin-data-class-lab/explore-data-class.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-data-class.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Kotlin

课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip

下载课程关联工程包:Kotlin

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2141.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习