"""Offline Kotlin 2.x semantic verifier for Chapter 16 (scope-functions)."""
from dataclasses import dataclass
import json
import sys
from typing import Any, Callable, Generic, TypeVar
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
T = TypeVar("T")
R = TypeVar("R")
def kt_let(obj: T, block: Callable[[T], R]) -> R:
"""it -> lambda result"""
return block(obj)
def kt_run_ext(obj: T, block: Callable[[T], R]) -> R:
"""this -> lambda result"""
return block(obj)
def kt_run_block(block: Callable[[], R]) -> R:
"""non-extension run -> lambda result"""
return block()
def kt_with(receiver: T, block: Callable[[T], R]) -> R:
"""non-extension with(receiver) { this } -> lambda result"""
return block(receiver)
def kt_apply(obj: T, block: Callable[[T], Any]) -> T:
"""this -> receiver itself (discards lambda return value)"""
block(obj)
return obj
def kt_also(obj: T, block: Callable[[T], Any]) -> T:
"""it -> receiver itself (discards lambda return value)"""
block(obj)
return obj
class KtResult(Generic[T]):
"""Models kotlin.Result<T> returned by runCatching."""
def __init__(self, value: T | None = None, error: BaseException | None = None) -> None:
self._value = value
self._error = error
@property
def is_success(self) -> bool:
return self._error is None
@property
def is_failure(self) -> bool:
return self._error is not None
def get_or_null(self) -> T | None:
return self._value if self._error is None else None
def get_or_default(self, default: T) -> T:
return self._value if self._error is None else default # type: ignore[return-value]
def exception_or_null(self) -> BaseException | None:
return self._error
def on_success(self, action: Callable[[T], None]) -> "KtResult[T]":
if self._error is None:
action(self._value) # type: ignore[arg-type]
return self
def on_failure(self, action: Callable[[BaseException], None]) -> "KtResult[T]":
if self._error is not None:
action(self._error)
return self
def kt_run_catching(block: Callable[[], T]) -> KtResult[T]:
try:
return KtResult(value=block())
except Exception as exc:
return KtResult(error=exc)
@dataclass
class Site:
name: str = ""
url: str = ""
visits: int = 0
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: The 5-scope-function matrix (receiver this/it x return lambda/receiver)
matrix = {
"let": {"ref": "it", "returns": "lambda_result", "extension": True, "since": "1.0"},
"run": {"ref": "this", "returns": "lambda_result", "extension": True, "since": "1.0"},
"with": {"ref": "this", "returns": "lambda_result", "extension": False, "since": "1.0"},
"apply": {"ref": "this", "returns": "receiver", "extension": True, "since": "1.0"},
"also": {"ref": "it", "returns": "receiver", "extension": True, "since": "1.1"},
}
actual_1 = {
"matrix": matrix,
"all_five_are_inline": True,
"it_group": [k for k, v in matrix.items() if v["ref"] == "it"],
"receiver_return_group": [k for k, v in matrix.items() if v["returns"] == "receiver"],
}
expected_1 = {
"matrix": matrix,
"all_five_are_inline": True,
"it_group": ["let", "also"],
"receiver_return_group": ["apply", "also"],
}
cases.append({
"name": "scope_function_5x2_matrix",
"summary": "Verify all 5 scope functions' reference mode (this vs it), return semantics, extension form, and inline status.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: let (nullable ?.let + transform), run (extension + block), with (StringBuilder)
site_opt: str | None = "www.mbsky.com"
null_opt: str | None = None
let_len = kt_let(site_opt, lambda it: len(it)) if site_opt is not None else 0
null_elvis = (kt_let(null_opt, lambda it: len(it)) if null_opt is not None else None)
null_elvis = null_elvis if null_elvis is not None else 0
parsed_site = kt_let("MBSKY|www.mbsky.com", lambda txt: Site(*txt.split("|")))
s_run = Site("mbsky", "www.mbsky.com")
def _run_body(this: Site) -> str:
this.name = this.name.upper()
return f"{this.name} -> {this.url}"
run_info = kt_run_ext(s_run, _run_body)
run_total = kt_run_block(lambda: 10 + 20)
buf: list[str] = []
def _with_body(this: list[str]) -> str:
this.append("Mbsky")
this.append(" - ")
this.append("www.mbsky.com")
return "".join(this)
with_text = kt_with(buf, _with_body)
actual_2 = {
"let_len": let_len,
"null_elvis_len": null_elvis,
"let_parsed_site": [parsed_site.name, parsed_site.url],
"run_info": run_info,
"run_mutated_name": s_run.name,
"run_block_total": run_total,
"with_text": with_text,
}
expected_2 = {
"let_len": 13,
"null_elvis_len": 0,
"let_parsed_site": ["MBSKY", "www.mbsky.com"],
"run_info": "MBSKY -> www.mbsky.com",
"run_mutated_name": "MBSKY",
"run_block_total": 30,
"with_text": "Mbsky - www.mbsky.com",
}
cases.append({
"name": "let_run_and_with_semantics",
"summary": "Verify let nullable chaining/transform, extension & block run, and non-extension with.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: apply (object config returning receiver) & also (side-effect chaining)
def _cfg(this: Site) -> None:
this.name = "MBSKY"
this.url = "www.mbsky.com"
this.visits = 100
configured = kt_apply(Site(), _cfg)
also_log: list[str] = []
chained_list = kt_also(
kt_also(["Mbsky", "MBSKY"], lambda it: also_log.append(f"size={len(it)}")),
lambda it: it.append("www.mbsky.com"),
)
actual_3 = {
"apply_configured": [configured.name, configured.url, configured.visits],
"also_side_effect_log": also_log,
"also_final_list": chained_list,
}
expected_3 = {
"apply_configured": ["MBSKY", "www.mbsky.com", 100],
"also_side_effect_log": ["size=2"],
"also_final_list": ["Mbsky", "MBSKY", "www.mbsky.com"],
}
cases.append({
"name": "apply_and_also_receiver_return",
"summary": "Verify apply object initialization and also side-effect chaining both return the receiver.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: runCatching & Result API + common pitfalls (apply discarding uppercase, it shadowing, safe call)
fail_res = kt_run_catching(lambda: int("MBSKY"))
ok_res = kt_run_catching(lambda: int("100"))
hooks: list[str] = []
fail_res.on_failure(lambda e: hooks.append(f"fail:{type(e).__name__}"))
ok_res.on_success(lambda v: hooks.append(f"ok:{v}"))
wrong_apply = kt_apply("mbsky", lambda this: this.upper())
right_run = kt_run_ext("mbsky", lambda this: this.upper())
words = ["mbsky", "kotlin"]
named_nested = [kt_let(word, lambda text: f"[{text}]") for word in words]
actual_4 = {
"fail_flags": [fail_res.is_success, fail_res.is_failure, fail_res.get_or_null(), fail_res.get_or_default(0)],
"ok_value": ok_res.get_or_null(),
"result_hooks": hooks,
"pitfall_apply_returns_original": wrong_apply,
"fix_run_returns_upper": right_run,
"explicit_named_nested": ", ".join(named_nested),
"runcatching_catches_cancellation_warning": True,
}
expected_4 = {
"fail_flags": [False, True, None, 0],
"ok_value": 100,
"result_hooks": ["fail:ValueError", "ok:100"],
"pitfall_apply_returns_original": "mbsky",
"fix_run_returns_upper": "MBSKY",
"explicit_named_nested": "[mbsky], [kotlin]",
"runcatching_catches_cancellation_warning": True,
}
cases.append({
"name": "runcatching_result_and_pitfalls",
"summary": "Verify runCatching/Result methods, apply return pitfall vs run, and nested lambda explicit parameter naming.",
"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-scope-functions-lab/explore-scope-functions.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-scope-functions.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2165.zip