【发布时间】:2021-06-29 06:22:06
【问题描述】:
TypeScript 允许以非常漂亮、干净和 100% 类型安全的方式构建类似数据的 DSL。我想知道在 Kotlin 中是否有可能?
例如,在下面的 TypeScript 代码 (playground) 中,我们定义了数据表的列。它检查值是否正确(字符串枚举),检查所有可选/必填字段,自动完成等。它开箱即用,您需要做的就是定义类型。
是否可以在 Kotlin 中使用类似的东西? 可以使用 Java Builder-pattern,但并不理想,并且需要为 builder-method 编写大量代码。另外,Kotlin 没有办法使用"number" 枚举,它会是Type.number,看起来不太好。或者也许我遗漏了一些东西,并且有一种方法可以在 Kotlin 中构建漂亮而干净的 DSL,而无需太多样板代码?
// Defining DSL ---------------------------------------------
type Type = "string" | "number" | "boolean" | "unknown"
interface StringFormatOptions {
type: "string"
}
interface LineFormatOptions {
type: "line"
ticks?: number[]
}
interface Column {
type: Type
format?: StringFormatOptions | LineFormatOptions
}
// Using DSL ------------------------------------------------
const columns: Column[] = [
{
type: "number",
format: { type: "line", ticks: [1000] }
},
{
type: "string"
}
]
【问题讨论】:
-
有个不错的项目AutoDSL,但是不支持Kotlin 1.4+
标签: kotlin