https://kotlinlang.org logo
Title
s

Sudhir Singh Khanger

02/27/2021, 3:30 AM
// generated by JsonToKotlinClass
data class JsonToKotlinClass(
    val `data`: List<Data?>?
) {
    data class Data(
        val id: Int?
    )
}

// generated by RoboPOJOGenerator
data class RoboPOJOGenerator(
    val data: List<DataItem?>? = null
)

data class DataItem(
    val id: Int? = null
)

fun main() {
    val jsonToKotlinClassData: JsonToKotlinClass.Data = JsonToKotlinClass.Data(1)
    val roboPOJOGeneratorData: DataItem = DataItem(1)
}
The former is generated by JsonToKotlinClass plugin and latter is generated by RoboPOJOGenerator. Which one would you prefer? Besides differences in syntax and how they are used are there other pros and cons of these two approaches.
j

jbnizet

02/27/2021, 7:34 AM
I hate both of them TBH. I would write the code by myself, document it, make the list not nullable (I’ve never seen in a case where having no list has a different meaning from having an empty list), make Data/DataItem not nullable (why would you accept null elements in a list of data?), and probably make id not nullable too (because I guess a null id should never happen).
☝️🏻 1
n

nanodeath

02/27/2021, 5:39 PM
agree that something like this would be nicer:
data class Foo(val data: List<DataItem>)
or maybe
data class Foo(val data: List<DataItem> = emptyList())
there's still the question of whether the other type should be an inner class or not, but 1. doesn't really matter, and 2. it depends on whether that type is constructed exclusively by
Foo
or not, IMO.
s

Sudhir Singh Khanger

02/28/2021, 4:39 AM
Nullable-or-otherwise is a valid argument and something I should look into. I am not sure how Retrofit handles it. Thanks for pointing it out. But I am mostly interested in the discussion of separate classes vs inner classes thing. One good and slightly verbose thing about inner classes is that I have to clearly use
JsonToKotlinClass.Data
.
j

jbnizet

02/28/2021, 9:44 AM
It’s a nested class, not an inner class. And you can just add an import for it and use it as if it was not nested.
s

Sudhir Singh Khanger

02/28/2021, 1:12 PM
Any non-syntactic pros and cons of using nested classes vs separate data classes?
n

nanodeath

02/28/2021, 2:49 PM
sorry to me it'll always be an inner class, just a static inner class 😛 maybe I should correct that. non-syntactic differences...well, you can always add the
inner
keyword to the, ahem, nested class, and then it can access instance state of the enclosing class. but if you don't, not really any differences.
🙏🏽 1