Can you define methods directly in data classes, o...
# getting-started
e
Can you define methods directly in data classes, or do you define them in the same file as extension methods? I tried Googling this but couldn’t find a definitive answer.
r
c
Hey there Ellen. You sure can!
Copy code
data class Name(val first: String, val last: String){
    fun getFullName(): String =
        "$first $last"
}
If we run that in a Kotlin scratch file in Android Studio we get:
oops Ruckus beat me to it 🙂
r
A scratch file is another great place to test
plus1 1
e
You all are right. I could have tested it. Let me ask a follow-up question: Should you define other methods in data classes.
c
That’ll prolly have a lot of opinions, but on my team we use them when needed.
🙏 1
Little old but here’s a discussion on reddit. I like the one comment that talks about separation of concerns, but also realizing sometimes it may make sense. https://www.reddit.com/r/Kotlin/comments/ehqe4e/why_is_it_bad_practice_to_have_functions_in_data/
in our codebase, a large majority are simple data classes, and usually if we need to do some simple “display to ui” or some such thing we’ll tend to put it in there vs an extension or transformer, etc.. ymmv of course
e
Are extension methods any better stylistically then defining the method within the data class?
Extension functions seem to violate separation of concerns just as much.
c
i’d prolly defer to what you or your team thinks feels better. I don’t think so tho really. iirc there’s no real overhead with extension methods for the most part
e
I’m doing an external code review in the absence of a Kotlin style guide and am trying to decide whether to say anything about the extension functions in the [same file as the] data class.
c
we have a couple of patterns in our codebase, the “newest” one being to have a
FooExts.kt
file that all extensions can go into for easy discoverability IF we think they’d be useful “globally”. Otherwise private extensions in the same file where it’s used works for us.
🙏 1
m
If the extensions are defined in the same file, then what’s the point of using them? In that case, to me it’s better just define those inside the data class. I mainly write extensions for: • 3rd party types I don’t control • my types but only localized in a certain point where that logic is cohesive with the rest, for example a conversion in a DAO or Port component
r
If the extensions are defined in the same file, then what’s the point of using them?
This article gives a good explanation as to the point.
m
Thanks, read it, but still not convinced. Probably Roman’s example wasn’t good enough, but I still prefer my approach.