Understanding @Immutable in Jetpack Compose
Emanuel T?nas?
??Kotlin Multiplatform Engineer. ??Empowering the next gen of Android Innovators.?? AI Enthusiast
In Jetpack Compose, @Immutable is an annotation used to mark a data class or type as immutable. This annotation helps the Compose runtime in optimizing the recomposition of composables. Let's break this down a bit:
What is Immutability?
Immutability, in simple terms, means that once an object is created, its state or data cannot be changed. If you need an object with different data, you create a new object rather than modifying the existing one.
Role of @Immutable in Jetpack Compose:
Usage Example:
Suppose you have a data class representing a user:
@Immutable
data class User(val name: String, val age: Int)
When you pass an instance of User to a composable function, the Compose runtime knows that this instance won't change. If the User object is part of the state that triggers recomposition, Compose will only recompose when the instance of User changes, not when the contents of User would have changed (because they can't).
Best Practices:
领英推荐
Do You Need @Immutable on Data Classes with Primitives?
Example
Consider the following data class:
data class UserProfile(val name: String, val age: Int)
Even though name (a String) and age (an Int) are immutable, marking UserProfile as @Immutable provides explicit clarity:
@Immutable data class UserProfile(val name: String, val age: Int)
Conclusion
While it's not strictly necessary to annotate data classes with @Immutable when they only contain primitive immutable types, doing so can be beneficial for clarity and potentially for optimization within the Compose framework. It explicitly communicates the immutability of the class and ensures that the Compose runtime treats it accordingly.