第 10 章 · 实战项目:Kotlin Todo CLI

把前 9 章学的所有东西串起来 —— 在浏览器里就能"跑"这个 CLI 工具。

💻 在线 CLI 模拟器(不用装环境)

下面这个 terminal 模拟了真正的 Todo CLI。试试 add / list / done / rm / stats。

$ todo

🏗 项目架构

todo-cli/
├── build.gradle.kts        # 构建脚本
├── settings.gradle.kts
└── src/main/kotlin/
    ├── Main.kt             # 入口 + 调度
    ├── Todo.kt             # 数据模型
    ├── Command.kt          # 命令模型 + 解析
    └── Repository.kt       # JSON 持久化

📦 各模块职责

Main.kt
runBlockingwhentry-catch 程序入口。调用 CommandParser 解析参数,dispatch 到不同 Command 处理。
Todo.kt
data classenum扩展函数 数据模型。Todo data class + Priority enum + 美化打印的扩展函数。
Command.kt
sealed classobjectwhen 命令模型。sealed Command 表达"命令是 Add/Done/Remove/List/Stats/Help 之一"。
Repository.kt
object协程JSONwithContext 数据持久化。object 单例 + suspend 函数把 IO 切到 IO 线程池。

🔄 数据流

用户输入 args
    ↓
CommandParser.parse(args)         // 解析成 Command sealed class
    ↓
execute(cmd: Command)
    ↓
Repository.load()                  // suspend,IO 线程读 JSON
    ↓
when (cmd) { ... }                 // 业务处理
    ↓
Repository.save(updatedTodos)      // suspend,IO 线程写 JSON
    ↓
println(...)                       // 用户输出

📚 这个项目用到了哪些 Kotlin 知识?

章节 知识点 在哪用了
第 1 章 Kotlin 语言基础 全程
第 2 章 Gradle 项目 build.gradle.kts 含 plugins / dependencies / application
第 3 章 val/var/字符串模板/when/范围/控制流 几乎所有文件
第 4 章 默认参数 + 命名参数 + 扩展函数 + lambda Todo 构造、format() 扩展、List 操作
第 5 章 Null 安全(?. ?: ?.let) CLI 参数解析、due 字段、错误处理
第 6 章 data class / enum / sealed class / object Todo / Priority / Command / Repository
第 7 章 集合操作(filter/map/groupingBy/sortedWith) list 命令的筛选 + 排序,stats 的统计
第 8 章 作用域函数(runCatching、let) Repository 加载错误处理
第 9 章 协程(runBlocking + suspend + withContext + Dispatchers) main 入口 + Repository.load/save 异步 IO

🚀 完成后你能做的事

  • 把这个项目放到 GitHub,简历上多一个 Kotlin 作品
  • 替换数据层为 SQLite,体验 Kotlin Exposed
  • 用 Ktor 暴露 HTTP API,把 CLI 变 Web 服务
  • 用 Kotlin Multiplatform 把数据层共享,做一个 Android 客户端
  • 用 GraalVM Native Image 编译成原生二进制,启动 30ms