Kotlin 教程
系统介绍 Kotlin 静态类型定位、Kotlin 2.2 教程路线、首个 .kt 入口程序与面向对象 Greeter 示例、四大语言优势以及官方学习与在线运行入口。
学完这一章,你能够
- 系统介绍 Kotlin 静态类型定位、Kotlin 2.2 教程路线、首个 .kt 入口程序与面向对象 Greeter 示例、四大语言优势以及官方学习与在线运行入口。
Kotlin 语言定位与教程范围
Kotlin 是由 JetBrains 开发的现代静态类型编程语言,最初面向 Java 虚拟机(JVM)构建,并已扩展支持编译为 Java 字节码、JavaScript、WebAssembly 以及原生机器码,从而覆盖服务端、Android 移动端与无 JVM 运行环境。Kotlin 以语法简洁、内置空安全类型系统和与 Java 双向无缝互操作著称,已成为 Android 开发的官方首选语言。本系列教程基于 Kotlin 2.2 编排,从基础语法、面向对象、集合与泛型一直延伸到协程与工程构建实践。
第一个 Kotlin 程序:最简入口与面向对象写法
Kotlin 源码文件统一使用 `.kt` 作为扩展名(例如 `hello.kt`、`app.kt`)。在最简版可执行程序中,文件顶部可选择声明 `package hello`,随后在顶层定义入口函数 `fun main(args: Array<String>)`(自 Kotlin 1.3 起若不读取命令行参数亦可简写为无参 `fun main()`),函数体内调用 `println("Hello World!")` 输出文本且语句末尾无需分号。本站离线验证脚本核对了 `.kt` 源码结构、包头与入口签名及本地未安装 `kotlinc` 的工具链状态。
Kotlin 同样支持紧凑的面向对象语法:通过 `class Greeter(val name: String)` 即可在主构造器中直接声明只读属性,并在成员函数 `greet()` 中用字符串模板 `"Hello, $name"` 插值输出;实例化时无需 `new` 关键字,直接调用 `Greeter("World!").greet()` 即可执行。离线验证脚本已模拟 `Greeter` 的只读 `val` 属性拦截与字符串模板求值结果 `Hello, World!`。
选择 Kotlin 的四大理由与官方参考入口
开发者选择 Kotlin 主要基于四项核心收益:一是简洁性,数据类、属性访问器与类型推断显著削减样板代码;二是安全性,编译器区分非空与可空类型并借助安全调用与 Elvis 兜底在编译期拦截大量空指针异常;三是互操作性,可直接复用 JVM、Android 与浏览器既有生态库;四是工具友好,不仅得到 IntelliJ IDEA 与 Android Studio 原生支持,也可使用 `kotlinc`、Gradle 或 Maven 在命令行完成构建。
进一步查阅语言规范与动手试跑代码,可直接访问 Kotlin 官方网站(https://kotlinlang.org/)、官方示例集合(https://play.kotlinlang.org/byExample/overview)以及免安装在线演练场 Kotlin Playground(https://play.kotlinlang.org/)。
离线校验 Kotlin 首个 .kt 程序、Greeter 类与空安全预演
"""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()
- 在本地 CPython 3.12.14 离线脚本中确认 kotlinc 缺席状态、最简 main 入口、Greeter 只读属性与模板输出、空安全预览及官方入口清单全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
当前源码 SHA256:3fc6e27b731c1edf960542bffe84a8f6ecc3a2f5a372990817718963d88d8911
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Kotlin 2.x 语义验证器(本地未安装 kotlinc/JVM Kotlin 工具链)。
ZIP SHA256:37428d38f65bba8bf5a9086c1ae4375942c5bfdfc37a7fba6790e2fc3d8d460a
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Kotlin 中实例化类为什么不需要 `new` 关键字,且 `class Greeter(val name: String)` 中的 `val` 起到什么作用?
展开参考解答
Kotlin 把构造器调用统一为普通函数调用语法,省略了冗余的 `new`;主构造器参数前加 `val` 会自动生成对应的只读属性与 getter,实例化后不可重新赋值。