首页 > 解决方案 > 有没有办法使用数据生成 kotlin dsl

问题描述

我们使用 kotlin dsl 作为用户友好的构建器来获取输入和生成数据。有没有办法做相反的事情?即,将现有数据转换为 dsl ?

这个 kotlin 表示可以转换为 dsl 吗?

val person = Person("John", 25)
val person = person {
    name = "John"
    age = 25
}

标签: kotlinkotlin-dsl

解决方案


除非你真的很喜欢{逗号,否则下面是绝对有效的 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)
}

但为什么要这样做?


推荐阅读