"""Offline Kotlin 2.x semantic verifier for Chapter 19 (interface)."""
from abc import ABC, abstractmethod
import json
import sys
from typing import Callable
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
class SiteIface(ABC):
@abstractmethod
def name(self) -> str:
...
def url(self) -> str:
return "www.mbsky.com"
def info(self) -> str:
return f"站点:{self.name()},地址:{self.url()}"
class FullSite(SiteIface):
def name(self) -> str:
return "MBSKY"
def url(self) -> str:
return "https://www.mbsky.com"
class SimpleSite(SiteIface):
def name(self) -> str:
return "Mbsky"
class NamedProp(ABC):
@property
@abstractmethod
def name(self) -> str:
...
@property
def display_name(self) -> str:
return f"[{self.name}]"
@property
@abstractmethod
def visits(self) -> int:
...
@visits.setter
@abstractmethod
def visits(self, value: int) -> None:
...
class SitePropImpl(NamedProp):
def __init__(self, name: str) -> None:
self._name = name
self._visits = 0
@property
def name(self) -> str:
return self._name
@property
def visits(self) -> int:
return self._visits
@visits.setter
def visits(self, value: int) -> None:
self._visits = value
class A:
def foo(self) -> str:
return "A.foo"
@property
def label(self) -> str:
return "A.label"
class B:
def foo(self) -> str:
return "B.foo"
@property
def label(self) -> str:
return "B.label"
class C(A, B):
def foo(self) -> str:
return A.foo(self) + " | " + B.foo(self)
@property
def label(self) -> str:
return A.label.fget(self) + " | " + B.label.fget(self) # type: ignore[misc]
class Base:
def base(self) -> str:
return "Base"
class Left(Base):
def left(self) -> str:
return "Left"
class Right(Base):
def base(self) -> str:
return "Right 重写了 Base"
def right(self) -> str:
return "Right"
class DiamondImpl(Left, Right):
def base(self) -> str:
return Right.base(self)
class Validator:
"""Models Kotlin 1.4+ `fun interface Validator` with one abstract method + default helper."""
def __init__(self, fn: Callable[[str], bool]) -> None:
self._fn = fn
def validate(self, text: str) -> bool:
return self._fn(text)
def describe(self) -> str:
return "校验器"
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Interface abstract + default methods & polymorphic list
actual_1 = {
"full_override": FullSite().info(),
"default_inherited": SimpleSite().info(),
"interface_members_default_public_open": True,
"interface_can_have_constructor": False,
}
expected_1 = {
"full_override": "站点:MBSKY,地址:https://www.mbsky.com",
"default_inherited": "站点:Mbsky,地址:www.mbsky.com",
"interface_members_default_public_open": True,
"interface_can_have_constructor": False,
}
cases.append({
"name": "interface_default_methods_and_impl",
"summary": "Verify interface abstract/default methods, default public+open semantics, and multiple implementation.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Interface properties (abstract val/var + default getter, no backing field/initializer)
sp = SitePropImpl("MBSKY")
sp.visits = 100
actual_2 = {
"default_getter_display_name": sp.display_name,
"impl_var_visits": sp.visits,
"interface_property_allows_backing_field": False,
"interface_property_allows_initializer": False,
}
expected_2 = {
"default_getter_display_name": "[MBSKY]",
"impl_var_visits": 100,
"interface_property_allows_backing_field": False,
"interface_property_allows_initializer": False,
}
cases.append({
"name": "interface_properties_no_backing_field",
"summary": "Verify interface abstract properties, default getter properties, and prohibition of backing fields/initializers.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Multi-interface conflict disambiguation (method + property) & diamond interface inheritance
c = C()
d = DiamondImpl()
actual_3 = {
"conflict_foo": c.foo(),
"conflict_label": c.label,
"diamond_methods": [d.base(), d.left(), d.right()],
}
expected_3 = {
"conflict_foo": "A.foo | B.foo",
"conflict_label": "A.label | B.label",
"diamond_methods": ["Right 重写了 Base", "Left", "Right"],
}
cases.append({
"name": "multi_interface_and_diamond_disambiguation",
"summary": "Verify super<Interface> disambiguation for methods/properties and diamond interface inheritance.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: fun interface SAM conversion (Kotlin 1.4+)
def check(text: str, validator: Validator) -> str:
return f"「{text}」通过校验" if validator.validate(text) else f"「{text}」未通过校验"
not_empty = Validator(lambda it: len(it) > 0)
shorter = Validator(lambda it: len(it) <= 10)
actual_4 = {
"not_empty_checks": [check("MBSKY", not_empty), check("", not_empty)],
"shorter_check": check("www.mbsky.com", shorter),
"default_member_describe": shorter.describe(),
"fun_interface_since": "1.4",
"fun_interface_allows_suspend_sam": False,
}
expected_4 = {
"not_empty_checks": ["「MBSKY」通过校验", "「」未通过校验"],
"shorter_check": "「www.mbsky.com」未通过校验",
"default_member_describe": "校验器",
"fun_interface_since": "1.4",
"fun_interface_allows_suspend_sam": False,
}
cases.append({
"name": "fun_interface_sam_conversion",
"summary": "Verify Kotlin 1.4+ fun interface SAM conversion, non-abstract member coexistence, and suspend restriction.",
"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-interface-lab/explore-interface.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-interface.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2152.zip