Kotlin DSL
💬 什么是 Kotlin DSL?
DSL 就像你用 Kotlin 写的“小语言”或“专属语法”。
比如你写一个配置文件或者描述页面内容时,希望这样写:
1 | page { |
看起来像“自己发明的语言”,对吧?这个就是 Kotlin DSL 的目标:写出接近自然语言的代码,让代码更“会说话”。
🧱 怎么做?用 Kotlin 的 3 个小技巧就可以了:
1️⃣ 高阶函数(函数里面传函数)
1 | fun doSomething(block: () -> Unit) { |
你可以这样用:
1 | doSomething { |
2️⃣ Lambda with Receiver(这个超重要,是 DSL 的核心)
看个例子:
1 | class Person { |
这样用:
1 | val p = createPerson { |
是不是很像自己在写一门“人类建造语言”?这就是 DSL 的味道!
3️⃣ apply
是帮你省代码的神器
等价于:
1 | val person = Person() |
写成:
1 | val person = Person().apply { |
🛠 我们做个最简单的 DSL 示例:构建菜单
我们希望能这样写代码:
1 | menu { |
👉 DSL 实现代码:
1 | class Menu { |
✅ 使用:
1 | val myMenu = menu { |
输出:
1 | 菜单内容: |
✅ 小结一句话:
Kotlin DSL = 自己写一个函数(用 lambda with receiver) + 定义类结构 +
apply()
,就能造出一套看起来像“自己写的语言”的代码。
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.