4

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
}
sdb
  • 327
  • 3
  • 12
  • 2
    what are you trying to do exactly? convert 1st snippet to 2nd one? – Govinda Sakhare Jun 21 '20 at 11:49
  • You could easily make an Android Studio plugin that interacts with Kotlin code using the PSI – user Jun 21 '20 at 12:56
  • @GovindaSakhare yes to be precise, I am trying to convert existing objects to DSL representation. – sdb Jun 21 '20 at 13:46
  • @user please elaborate. – sdb Jun 21 '20 at 13:47
  • See [this](https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started.html) on creating plugins. You can use an [editor event](https://www.jetbrains.org/intellij/sdk/docs/tutorials/editor_basics/editor_events.html?search=event) to turn Kotlin code into the DSL form – user Jun 21 '20 at 19:21

1 Answers1

4

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?

madhead
  • 31,729
  • 16
  • 153
  • 201