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

离线校验 Kotlin 首个 .kt 程序、Greeter 类与空安全预演

PYTHONWindows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。explore-tutorial.py
explore-tutorial.py148 行
"""Offline Kotlin 2.x semantic verifier for Chapter 01 (tutorial)."""
import json
import re
import shutil
import sys

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


class Greeter:
    """Models Kotlin `class Greeter(val name: String) { fun greet() ... }`."""

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

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

    def greet(self) -> str:
        return f"Hello, {self.name}"


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

    # Case 1: toolchain absence check + .kt source entry structure
    kotlinc_bin = shutil.which("kotlinc")
    kotlin_bin = shutil.which("kotlin")
    hello_src = (
        "package hello\n\n"
        "fun main(args: Array<String>) {\n"
        '    println("Hello World!")\n'
        "}\n"
    )
    has_pkg = bool(re.search(r"^package\s+hello\b", hello_src, re.M))
    has_main = bool(re.search(r"fun\s+main\s*\(args:\s*Array<String>\)", hello_src))
    no_semicolon = ";" not in hello_src
    output_hello = "Hello World!\n"
    actual_1 = {
        "kotlinc_installed": kotlinc_bin is not None,
        "kotlin_installed": kotlin_bin is not None,
        "extension": ".kt",
        "has_package": has_pkg,
        "has_main_entry": has_main,
        "semicolon_omitted": no_semicolon,
        "stdout": output_hello,
    }
    expected_1 = {
        "kotlinc_installed": False,
        "kotlin_installed": False,
        "extension": ".kt",
        "has_package": True,
        "has_main_entry": True,
        "semicolon_omitted": True,
        "stdout": "Hello World!\n",
    }
    cases.append({
        "name": "minimal_hello_and_toolchain_probe",
        "summary": "Verify .kt file convention, package/main syntax, omitted semicolons, expected stdout, and local kotlinc absence.",
        "expected": expected_1,
        "actual": actual_1,
        "passed": actual_1 == expected_1,
    })

    # Case 2: OO Greeter class without `new` keyword + string template `$name`
    greeter = Greeter("World!")
    read_only_blocked = False
    try:
        greeter.name = "Other"  # type: ignore[misc]
    except AttributeError:
        read_only_blocked = True
    actual_2 = {
        "greeting": greeter.greet(),
        "val_readonly_enforced": read_only_blocked,
        "instantiated_without_new": True,
    }
    expected_2 = {
        "greeting": "Hello, World!",
        "val_readonly_enforced": True,
        "instantiated_without_new": True,
    }
    cases.append({
        "name": "oop_greeter_val_template",
        "summary": "Model Kotlin class Greeter(val name: String), string template interpolation, and val immutability.",
        "expected": expected_2,
        "actual": actual_2,
        "passed": actual_2 == expected_2,
    })

    # Case 3: Kotlin core value propositions & null-safety preview
    pillars = ("concise", "safe", "interoperable", "tool-friendly")
    nullable_val: str | None = None
    safe_len = len(nullable_val) if nullable_val is not None else None
    elvis_len = safe_len if safe_len is not None else 0
    actual_3 = {
        "pillars_count": len(pillars),
        "safe_call_result": safe_len,
        "elvis_fallback": elvis_len,
        "target_version": "2.2",
    }
    expected_3 = {
        "pillars_count": 4,
        "safe_call_result": None,
        "elvis_fallback": 0,
        "target_version": "2.2",
    }
    cases.append({
        "name": "core_pillars_and_null_safety_model",
        "summary": "Check the four Kotlin design pillars and safe-call/Elvis null-handling semantics.",
        "expected": expected_3,
        "actual": actual_3,
        "passed": actual_3 == expected_3,
    })

    # Case 4: Official documentation & playground entry registry
    official_hosts = [
        "kotlinlang.org",
        "play.kotlinlang.org",
        "developer.android.com",
    ]
    actual_4 = {
        "official_hosts": official_hosts,
        "all_https_ready": all("." in h for h in official_hosts),
    }
    expected_4 = {
        "official_hosts": ["kotlinlang.org", "play.kotlinlang.org", "developer.android.com"],
        "all_https_ready": True,
    }
    cases.append({
        "name": "official_resources_inventory",
        "summary": "Validate official Kotlin documentation, examples, and online playground hosts.",
        "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-tutorial-lab/explore-tutorial.py

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

下载课程关联工程包:Kotlin

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

下载课程关联工程包:Kotlin

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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