https://kotlinlang.org logo
Title
k

Kevin

02/19/2019, 9:04 PM
I have a question about style. I have the following:
data class Attachment(val filename: String?, val mimeType: String?)

val Attachment.isImage: Boolean
    get() = this.mimeType?.contains("image") == true

fun Attachment.load(): Image { ... }
I want to keep my data classes as pure and simple as possible, and those extensions are just convenience methods for my UI and not core to the model. But I’m wondering if I should just define those things in the class itself?
s

snowe

02/19/2019, 9:07 PM
I would tend to only use extension functions for stuff you don’t control, or can’t easily modify. I wouldn’t use them like this. Of course if your goal is what you describe, maybe you feel differently, but it has the potential to be slower than a regular call as it’s accessed statically.
👍 1
k

karelpeeters

02/19/2019, 9:16 PM
A static call slower than a normal (possibly virtual) call? How could that possibly be true?
👍 1
s

snowe

02/19/2019, 9:17 PM
I guess it’s not. Ignore what I said.
k

Kevin

02/19/2019, 9:26 PM
That makes sense, I’ll put it in the class. Thanks 👍
s

serebit

02/19/2019, 9:45 PM
I tend to define extension functions for functionality that only uses the public members of the class, but that’s just my philosophy
👍 1
h

hudsonb

02/19/2019, 10:36 PM
If the UI is in a separate module I'd define them as internal ext functions in the UI module
k

Kevin

02/20/2019, 1:56 AM
It’s in a separate package if that’s what you mean. (I dunno if module has a technical meaning in kotlin?) I have a “model” package that just has data classes, and then I use those models in my “db” package and “ui” package.