hey all, creating a class inside another one is c...
# codingconventions
t
hey all, creating a class inside another one is considered a good practice? In my case, it represents an JSON that my controller will receive. The
EventFrom
only exists in this context of
TrackInfoDTO
. Or should I create another file only for
EventFrom
?
Copy code
data class TrackInfoDTO(
        val url: String,
        val userID: String,
        val eventFrom: EventFrom,
        val UTM: Map<String, Any>
) {
    data class EventFrom(
            val parentElementName: String,
            val elementName: String,
            val CTCurrent: String,
            val payload: Map<String, Any>
    )
}
also the fields
UTM
and
payload
can contain any key=value. Is this
Map<String, Any>
the best way to do ?
m
Not sure that nesting makes sense here. Would ‘force’ something outside to reference the class as
TrackInfoDTO.EventFrom
if the type gets defined. If that’s what you want… Side note. You don’t need to put
EventFrom
in its own file if its at the top-level. Kotlin supports multiple public classes in a single file. Don’t go crazy with it, but it is helpful for defining multiple related classes in one file for easier reading. This is a perfect example of when putting many classes in one file would make sense. All the JSON parsing data classes in one file is much easier to read than having to navigate a whole bunch of files.
👆 4
t
you mean like this?
Copy code
data class TrackInfoDTO(
        val url: String,
        val userID: String,
        val eventFrom: EventFrom,
        val UTM: Map<String, Any>
)

data class EventFrom(
        val parentElementName: String,
        val elementName: String,
        val CTCurrent: String,
        val payload: Map<String, Any>
)
just keep both classes in one file? is there a way to keep
EventFrom
private (cannot be initialized outside this file)?
t
mark it
private
t
but then this happens
t
Because
TrackInfoDTO
has a public constructor that accepts
EventFrom
- so
EventFrom
isn’t really just scoped to that file
You could make it public but just make the constructor private
t
Thanks!
Copy code
data class TrackDTO(
        val url: String,
        val userID: String,
        val eventFrom: EventFrom,
        val UTM: Map<String, Any>
)

data class EventFrom private constructor(
        private val parentElementName: String,
        private val elementName: String,
        private val CTCurrent: String,
        private val payload: Map<String, Any>
)
m
If the constructor is private, then how does it get built? I suspect this will cause issues with the JSON parser or whatever you’re using to build the objects, but your tests should tell you if I’m wrong or right on this.
t
Good question haha