https://kotlinlang.org logo
#stdlib
Title
# stdlib
y

yschimke

03/24/2023, 8:58 PM
Is there any utility for turning a hierarchy Kotlin data classes into code. Want to fetch some data from an API, and turn it into executable code for test fixtures.
z

Zac Sweers

03/24/2023, 8:59 PM
not a joke - ChatGPT is actually excellent at this
1
y

yschimke

03/24/2023, 9:04 PM
Give it the data classes, ask for better toString values.
d

darkmoon_uk

03/30/2023, 9:20 PM
I'm not sure exactly what you mean but it sounds like you want to serialise your classes; in which case I recommend
kotlinx.serialization
library.
y

yschimke

03/30/2023, 9:32 PM
No, I meant code I can copy and paste into my IDE to recreate a data class that would be exactly equal.
I think ruby had an inspect method
I don't need perfect, or handling all possible types. Just knowing to quote strings correctly
j

Joffrey

03/31/2023, 7:22 AM
Data classes are already code, though. Do you mean you want to turn JSON into code that creates data class instances with the same data?
y

yschimke

03/31/2023, 7:24 AM
I have an instance of an arbitrary data class at runtime. I want to turn it into a string I can put into my code to reinflate later
j

Joffrey

03/31/2023, 7:24 AM
Ah I see. I think someone has asked this question some time ago, but I don't remember the outcome
d

darkmoon_uk

03/31/2023, 8:38 AM
@yschimke are you sure you don't want
kotlinx.serialization
Turning instances of data classes into strings that can be reinflated later on is kind of it's thing
y

yschimke

03/31/2023, 8:39 AM
Maybe, but I don't want to have to use kotlinx serialisation on the other side. Just copy and paste.
I have other solutions. More curious if an inspect like operation is supported.
I'd like the final form to be affected by refactoring, for example
d

darkmoon_uk

03/31/2023, 8:40 AM
I think we need an example. I can't be alone in feeling I haven't fully grasped what you're looking for.
y

yschimke

03/31/2023, 8:44 AM
Copy code
val conferenceList = GetConferencesQuery.ConferenceList(conferences = listOf(
        GetConferencesQuery.Conference(
            "kotlinconf2023",
            listOf(
                LocalDate.parse("2023-04-12"),
                LocalDate.parse("2023-04-13"),
                LocalDate.parse("2023-04-14")
            ),
            "KotlinConf 2023"
        )
...

val textFixtureInspector = TestFixtureInspector()

println(textFixtureInspector.inspect(conferenceList))
And that output
Copy code
GetConferencesQuery.ConferenceList(conferences = listOf(
        GetConferencesQuery.Conference(
            id = "kotlinconf2023",
            dates = listOf(
                LocalDate.parse("2023-04-12"),
                LocalDate.parse("2023-04-13"),
                LocalDate.parse("2023-04-14")
            ),
            name = "KotlinConf 2023"
        )
3 Views