Is there a way to generate kotlin dsl using data

Viewed 269

We are using kotlin dsl to as a user friendly builder to take input and generate data. Is there a way to do the opposite of that ? ie, convert existing data into dsl ?

Can this kotlin representation be converted to dsl ?

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

Unless you're really crazy about { and some commas, below is an absolutely valid Kotlin code:

data class Person(
    val name: String,
    val age: Int
)

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

I seems really close to what you want and comes out-of-the-box.

Of course, you can achieve the syntax you want by writing some extra code, like:

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)
}

But why do that?

Related