kotlin - 有没有办法使用数据生成 kotlin dsl
问题描述
我们使用 kotlin dsl 作为用户友好的构建器来获取输入和生成数据。有没有办法做相反的事情?即,将现有数据转换为 dsl ?
这个 kotlin 表示可以转换为 dsl 吗?
val person = Person("John", 25)
val person = person {
name = "John"
age = 25
}
解决方案
除非你真的很喜欢{
逗号,否则下面是绝对有效的 Kotlin 代码:
data class Person(
val name: String,
val age: Int
)
val person = Person(
name = "John",
age = 25
)
我似乎真的很接近你想要的并且开箱即用。
当然,您可以通过编写一些额外的代码来实现您想要的语法,例如:
import kotlin.properties.Delegates
data class Person(
val name: String,
val age: Int
)
class PersonDSL{
lateinit var name: String
var age: Int by Delegates.notNull<Int>()
fun toPerson(): Person = Person(this.name, this.age)
}
fun person(config: PersonDSL.() -> Unit): Person{
val dsl = PersonDSL()
dsl.config()
return dsl.toPerson()
}
fun main(){
val person = person {
name = "John"
age = 25
}
println(person) // Person(name=John, age=25)
}
但为什么要这样做?
推荐阅读
- isabelle - Isabelle/HOL中如何实现声明类型和常量?
- angular - 如何使用 Angular 中的添加按钮添加输入字段?
- pandas - Python pandas数据框,如何获取设置的数字
- jmeter - Jmeter 不会在 CSV 上写入
- android - Android OS 导航和状态栏在全屏 PWA 上切换进出
- c - 为什么 setjmp() 在 windows 上取 2 个 args 而在 linux 上只取 1 个 args?
- python - Python - 命令/函数停止运行当前代码而不退出 python
- ios - 如何为非日期/时间值创建 iOS 的内联选择器
- spring-boot - 微服务无法连接到作为 docker 镜像运行的 AXON 服务器
- kubernetes - 错误:elasticsearch 没有部署的版本错误:插件“2to3”退出并出现错误