"""Offline Kotlin 2.x semantic verifier for Chapter 14 (lambda)."""
from dataclasses import dataclass
import json
import sys
from typing import Callable
VERSION = "CPython 3.12.14 offline Kotlin 2.x semantic verifier (kotlinc absent)"
@dataclass
class Site:
name: str
url: str = "www.mbsky.com"
def hello(self) -> str:
return f"你好,{self.name}"
def is_even(v: int) -> bool:
return v % 2 == 0
def calculate(a: int, b: int, op: Callable[[int, int], int]) -> int:
return op(a, b)
def multiplier(factor: int) -> Callable[[int], int]:
return lambda v: v * factor
def make_counter() -> Callable[[], int]:
count = 0
def inc() -> int:
nonlocal count
count += 1
return count
return inc
class StringChecker:
"""Models Kotlin `fun interface StringChecker { fun check(value: String): Boolean }`."""
def __init__(self, fn: Callable[[str], bool]) -> None:
self._fn = fn
def check(self, value: str) -> bool:
return self._fn(value)
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: Function types, nullable function type ?.invoke, receiver function type
sum_fn: Callable[[int, int], int] = lambda a, b: a + b
greet_fn: Callable[[str], str] = lambda name: f"你好,{name}"
callback: Callable[[int], int] | None = None
null_call = callback(21) if callback is not None else None
callback = lambda it: it * 2
non_null_call = callback(21) if callback is not None else None
repeat_fun: Callable[[str, int], str] = lambda this, times: this * times
actual_1 = {
"sum_1_2": sum_fn(1, 2),
"greet": greet_fn("Mbsky"),
"nullable_before_assign": null_call,
"nullable_after_assign": non_null_call,
"receiver_as_ext": repeat_fun("Sky", 2),
"receiver_as_plain": repeat_fun("MBSKY", 2),
}
expected_1 = {
"sum_1_2": 3,
"greet": "你好,Mbsky",
"nullable_before_assign": None,
"nullable_after_assign": 42,
"receiver_as_ext": "SkySky",
"receiver_as_plain": "MBSKYMBSKY",
}
cases.append({
"name": "function_types_and_receiver_lambdas",
"summary": "Verify function types, nullable function ?.invoke, and String.(Int) -> String interconversion.",
"expected": expected_1,
"actual": actual_1,
"passed": actual_1 == expected_1,
})
# Case 2: Lambda syntax, trailing lambda, higher-order functions, collection pipelines
double_it = lambda it: it * 2
second_unused = lambda _, value: value
sites = ["mbsky", "MBSKY", "java", "kotlin"]
upper_only = [s for s in sites if s == s.upper()]
lengths = [len(s) for s in sites]
chained = [s.upper() for s in sites if s.lower().startswith("m")]
indexed = [f"{i} -> {v}" for i, v in enumerate(["Mbsky", "www.mbsky.com"])]
map_entries = [f"{k} = {v}" for k, v in {"name": "Mbsky", "site": "www.mbsky.com"}.items()]
actual_2 = {
"double_5": double_it(5),
"unused_param_second": second_unused(1, 2),
"hof_add_mul": [calculate(6, 3, lambda a, b: a + b), calculate(6, 3, lambda a, b: a * b)],
"hof_returned_fn": [multiplier(3)(5), multiplier(10)(4)],
"filter_upper": upper_only,
"map_lengths": lengths,
"filter_map_chain": chained,
"original_immutable": sites,
"for_each_indexed": indexed,
"map_for_each": map_entries,
}
expected_2 = {
"double_5": 10,
"unused_param_second": 2,
"hof_add_mul": [9, 18],
"hof_returned_fn": [15, 40],
"filter_upper": ["MBSKY"],
"map_lengths": [5, 5, 4, 6],
"filter_map_chain": ["MBSKY", "MBSKY"],
"original_immutable": ["mbsky", "MBSKY", "java", "kotlin"],
"for_each_indexed": ["0 -> Mbsky", "1 -> www.mbsky.com"],
"map_for_each": ["name = Mbsky", "site = www.mbsky.com"],
}
cases.append({
"name": "lambdas_hofs_and_collection_ops",
"summary": "Verify Lambda syntax, it, _, trailing lambdas, HOFs, and immutable filter/map/forEachIndexed pipelines.",
"expected": expected_2,
"actual": actual_2,
"passed": actual_2 == expected_2,
})
# Case 3: Closures capturing mutable var + anonymous function local return
counter = 0
def inc_local() -> None:
nonlocal counter
counter += 1
inc_local()
inc_local()
c1 = make_counter()
c2 = make_counter()
c1(); c1(); c2()
anon_out: list[int] = []
def anon_fn(v: int) -> None:
if v == 3:
return # returns from anonymous function only
anon_out.append(v)
for item in [1, 2, 3, 4]:
anon_fn(item)
actual_3 = {
"captured_var_counter": counter,
"independent_closures": [c1(), c2()],
"anon_local_return_kept": anon_out,
"enclosing_continued": True,
}
expected_3 = {
"captured_var_counter": 2,
"independent_closures": [3, 2],
"anon_local_return_kept": [1, 2, 4],
"enclosing_continued": True,
}
cases.append({
"name": "closures_and_anonymous_function_return",
"summary": "Verify mutable var capture across independent closures and local return semantics of anonymous functions.",
"expected": expected_3,
"actual": actual_3,
"passed": actual_3 == expected_3,
})
# Case 4: Function references (::top, bound, unbound, constructor ::Site) & SAM conversion
site = Site("Mbsky", "www.mbsky.com")
bound_ref = site.hello
unbound_ref = Site.hello
ctor_ref = Site
pairs = [("Mbsky", "www.mbsky.com"), ("MBSKY", "kotlin.mbsky.com")]
created = [ctor_ref(n, u) for n, u in pairs]
checker = StringChecker(lambda s: len(s) > 0)
actual_4 = {
"top_ref_filter": [n for n in [1, 2, 3, 4] if is_even(n)],
"bound_ref": bound_ref(),
"unbound_ref": unbound_ref(site),
"ctor_ref_names": [s.name for s in created],
"sam_non_empty": [checker.check("Mbsky"), checker.check("")],
"kotlin_fun_interface_since": "1.4",
}
expected_4 = {
"top_ref_filter": [2, 4],
"bound_ref": "你好,Mbsky",
"unbound_ref": "你好,Mbsky",
"ctor_ref_names": ["Mbsky", "MBSKY"],
"sam_non_empty": [True, False],
"kotlin_fun_interface_since": "1.4",
}
cases.append({
"name": "callable_references_and_sam_conversion",
"summary": "Verify top-level/bound/unbound/constructor :: references and fun interface SAM conversion.",
"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-lambda-lab/explore-lambda.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-lambda.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联43章) · 含当前章节或实例 · mbskycom202612a2132.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2155.zip