https://kotlinlang.org logo
#compose
Title
# compose
s

Shahzad Ansari

02/22/2024, 6:39 PM
I am wondering if following approach is okay or it will become a problem down the line. I have been using this approach where I setup an empty
companion object
in my data models and define an extension property to get a sample for that data model lazily.
Copy code
data class User(val name: String, val age: Int) {
    companion object
}

val User.Companion.mock by lazy { User(name = "John", age = 25) }
And I use this mock property to get sample data for my
@Preview
in Jetpack Compose. Since code defined in
@Preview
composable does not become part of live app or APK, I am wondering if it's okay to use this approach.
Copy code
@Preview
@Composable
fun UserInfo() {
    Text(User.mock.toString())
}
s

Stylianos Gakis

02/22/2024, 9:39 PM
If it works for you why not? Might be a bit confusing/annoying to get the
mock
appear in autocomplete sometimes, but the alternatives aren't all that good either tbh
s

Shahzad Ansari

02/24/2024, 12:17 PM
Just curious if it's going to cause some performance issues because we are just starting with this approach and heavily creating Previews for our UI components.
s

Stylianos Gakis

02/24/2024, 12:18 PM
Performance of what?
s

Shahzad Ansari

02/24/2024, 12:21 PM
The app itself. Maybe we could run into a case where user has a very low end phone with limited memory and our app might be consuming too much already.
s

Stylianos Gakis

02/24/2024, 1:09 PM
Previews are not used from production code though, why would a function which creates an object which is not even used in the production app have an effect? You can make it a function instead of a lazy val if you are super concerned , but I would expect r8 to strip those out anyway
s

Shahzad Ansari

02/24/2024, 4:22 PM
fun
sounds safer. Thanks 👍
2 Views