Skip to content
AKarda-kazancimainbrew()
Personal blog
AK
arda-kazanci › journal ›kotlin-2-5-value-objects-android-mvi-state.md
← Journal.md
kotlin-2-5-value-objects-android-mvi-state.md239 lines · Markdown · UTF-8
Markdown Preview · kotlin-2-5-value-objects-android-mvi-state.md Rendered
journal/kotlin-2-5-value-objects-android-mvi-state.md

Kotlin 2.5.0-RC2 Value Objects: Modeling Android MVI State Without Identity

How Kotlin 2.5.0-RC2 value objects, multi-field value classes, sealed value classes, and name-based destructuring (KEEP-0454) shape Android MVI UI states, actions, and routes under -Xfull-value-classes.

Kotlin 2.5.0-RC2 (org.jetbrains.kotlin:kotlin-gradle-plugin:2.5.0-RC2) ships experimental support for full value classes and value objects under KEEP-0454. In an earlier look at Kotlin 2.5 full value classes, I walked through a single PlaybackRange model on Beta2. With RC2 out and name-based destructuring now stable by default, I wanted to see how value object, multi-field value class, and sealed value class hold up across a full Android MVI flow: UI state, user actions, navigation routes, and a StateFlow-backed ViewModel.

Enabling -Xfull-value-classes on AGP 9

To compile value object and multi-field value class declarations, point the project to Kotlin 2.5.0-RC2 and pass -Xfull-value-classes to the compiler. On AGP 9, as noted in the Kotlin 2.4.20 lazy assertion messages setup, kotlin-gradle-plugin must be declared on the root buildscript classpath so Gradle picks up the RC2 compiler.

gradle/libs.versions.toml
[versions]
kotlin = "2.5.0-RC2"
[libraries]
kotlin-gradle-plugin = { group = "org.jetbrains.kotlin", name = "kotlin-gradle-plugin", version.ref = "kotlin" }
app/build.gradle.kts
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xfull-value-classes")
}
}

Modeling an Android MVI state with value object and value class

Previously, a Kotlin value class could wrap only one property. Under KEEP-0454, a value class can hold multiple primary val properties, and a value object is the zero-property case: a unit type with one possible value and no object identity.

Here is a minimal screen state and renderer written with both:

NewsUiState.kt
sealed interface NewsUiState {
value object Loading : NewsUiState
value object Empty : NewsUiState
value class Error(val message: String, val canRetry: Boolean) : NewsUiState
value class Content(val title: String, val readMinutes: Int) : NewsUiState
}
fun render(state: NewsUiState) {
when (state) {
NewsUiState.Loading -> println("Loading...")
NewsUiState.Empty -> println("No articles found")
is NewsUiState.Error -> {
(val message, val canRetry) = state // name-based destructuring
println("Error: $message (retry=$canRetry)")
}
is NewsUiState.Content -> {
(val title, val readMinutes) = state
println("$title ($readMinutes min read)")
}
}
}

A few details jump out immediately when you compile this. First, Loading and Empty generate structural equals(), hashCode(), and a clean toString() ("Loading", "Empty"), just like data object. Second, neither Error nor Content generates componentN() functions. Kotlin 2.5.0-RC2 stabilizes name-based destructuring in only-syntax mode, so (val title, val readMinutes) = state matches by property name. Reordering properties in the primary constructor will not silently swap values at call sites.

Enforcing shared invariants with sealed value class

Regular interfaces can declare validation helpers, yet nothing forces every implementing class to invoke them during construction. KEEP-0454 adds abstract and sealed value classes to cover that gap.

An abstract or sealed value class cannot declare stored properties with backing fields. Concrete subclasses hold the primary val properties and pass constructor arguments up to the shared init block.

PageRange.kt
sealed value class PageRange(
startPage: Int,
endPage: Int,
) {
init {
require(startPage >= 1) { "startPage must be >= 1, was $startPage" }
require(startPage <= endPage) {
"startPage ($startPage) must not exceed endPage ($endPage)"
}
}
}
value class LoadedPageRange(
val startPage: Int,
val endPage: Int,
) : PageRange(startPage, endPage) {
// Computed properties without backing fields are allowed.
val totalPages: Int
get() = endPage - startPage + 1
}

Any concrete subclass of PageRange runs the init checks automatically during construction. Computed properties like totalPages remain legal because they do not allocate a backing field. Delegated properties such as by lazy are rejected by the compiler because a delegate requires hidden storage.

Wiring value objects into a StateFlow ViewModel

Expanding the minimal NewsUiState above for a paginated feed gives us NewsFeedUiState, alongside MVI intents, domain fetch results, and parameterless destinations (such as top-level tabs alongside type-safe Navigation 3 routes).

NewsFeedValueModels.kt
value class PaginationWindow(val page: Int, val pageSize: Int) {
init {
require(page >= 1) { "page must be >= 1, was $page" }
require(pageSize > 0) { "pageSize must be > 0, was $pageSize" }
}
val offset: Int
get() = (page - 1) * pageSize
}
value class ArticleSummary(
val id: String,
val title: String,
val readMinutes: Int,
) {
val isQuickRead: Boolean
get() = readMinutes <= 3
}
sealed interface NewsFeedUiState {
value object Idle : NewsFeedUiState
value object Loading : NewsFeedUiState
value object Empty : NewsFeedUiState
value class Error(val message: String, val canRetry: Boolean) : NewsFeedUiState
value class Content(
val query: String,
val pagination: PaginationWindow,
val loadedRange: LoadedPageRange,
val highlightedArticle: ArticleSummary,
val totalCount: Int,
) : NewsFeedUiState
}
sealed interface NewsFeedAction {
value object LoadInitial : NewsFeedAction
value object Refresh : NewsFeedAction
value object Retry : NewsFeedAction
value object ClearSearch : NewsFeedAction
value class Search(val query: String) : NewsFeedAction
value class SelectArticle(val articleId: String) : NewsFeedAction
value object NavigateBack : NewsFeedAction
}
sealed interface NewsRoute {
value object Feed : NewsRoute
value object Bookmarks : NewsRoute
value class ArticleDetail(val articleId: String, val fromSearch: Boolean) : NewsRoute
}
sealed interface FeedFetchResult {
value object NetworkUnavailable : FeedFetchResult
value object EmptyFeed : FeedFetchResult
value class Success(val highlightedArticle: ArticleSummary, val totalCount: Int) : FeedFetchResult
}

Because full value classes do not generate copy(), the ViewModel builds each next state through its primary constructor. On StateFlow, consecutive emissions with equal values deduplicate as expected through structural equals().

NewsFeedValueViewModel.kt
class NewsFeedValueViewModel(
private val source: NewsFeedSource,
) : ViewModel() {
private val _uiState = MutableStateFlow<NewsFeedUiState>(NewsFeedUiState.Idle)
val uiState: StateFlow<NewsFeedUiState> = _uiState.asStateFlow()
private val _currentRoute = MutableStateFlow<NewsRoute>(NewsRoute.Feed)
val currentRoute: StateFlow<NewsRoute> = _currentRoute.asStateFlow()
private var lastQuery: String = ""
fun onAction(action: NewsFeedAction) {
when (action) {
NewsFeedAction.LoadInitial -> load(query = "")
NewsFeedAction.Refresh, NewsFeedAction.Retry -> load(query = lastQuery)
NewsFeedAction.ClearSearch -> load(query = "")
is NewsFeedAction.Search -> {
(val query) = action
load(query = query)
}
is NewsFeedAction.SelectArticle -> {
(val articleId) = action
_currentRoute.value = NewsRoute.ArticleDetail(
articleId = articleId,
fromSearch = lastQuery.isNotBlank(),
)
}
NewsFeedAction.NavigateBack -> {
_currentRoute.value = NewsRoute.Feed
}
}
}
private fun load(query: String) {
lastQuery = query.trim()
_uiState.value = NewsFeedUiState.Loading
val pagination = PaginationWindow(page = 1, pageSize = 10)
_uiState.value = when (val result = source.fetch(lastQuery, pagination)) {
FeedFetchResult.NetworkUnavailable -> NewsFeedUiState.Error(
message = "No internet connection",
canRetry = true,
)
FeedFetchResult.EmptyFeed -> NewsFeedUiState.Empty
is FeedFetchResult.Success -> {
(val highlightedArticle, val totalCount) = result
NewsFeedUiState.Content(
query = lastQuery,
pagination = pagination,
loadedRange = LoadedPageRange(startPage = 1, endPage = 1),
highlightedArticle = highlightedArticle,
totalCount = totalCount,
)
}
}
}
}

For action types, domain results, and discrete sealed states where every branch is constructed fresh, the missing copy() method barely gets in the way. Where you do feel it is on a single large screen-state holder with 10 or 15 fields that updates one boolean at a time. The Kotlin team plans to address ergonomic updates separately under KT-44653 (copy vars).

Why prefer value classes and value objects over data classes

A data class is an ordinary identity-bearing class with generated boilerplate. Nothing stops a teammate from adding a var property to the constructor, stashing mutable state inside the class body (excluded from equals()), or attaching a by lazy cache. With data object, deserialization or reflection can produce a second instance at runtime, which breaks any code that accidentally relies on ===.

Full value classes enforce those boundaries at compile time:

  • Every stored property must be a primary constructor val. Body backing fields and delegated properties are disallowed.
  • value object declarations hold zero stored state.
  • Referential equality (===) is a compile-time error on value class and value object types.
  • Because a value object has no observable identity, the compiler is free to keep a canonical singleton instance or materialize the value on demand, while still running initialization once.

Compose stability and Stage 1 runtime limits

KEEP-0454 includes a dedicated section on Jetpack Compose. Today, the Compose compiler treats a data class coming from a separate pure-Kotlin Gradle module (such as :domain or :core:model, compiled without the Compose compiler plugin) as unstable unless you annotate it or list it in a stability configuration file. Because an MFVC guarantees that its primary properties are stored val fields with no custom getters, the Compose compiler can safely perform cross-module stability inference on it in the future.

Immutability is still shallow. If a value class stores a standard List<T>, that list can be backed by a MutableList at runtime, so Compose will still mark the enclosing type as unstable unless you use kotlinx.collections.immutable or explicit stability annotations. A value object has zero properties, so it avoids that problem completely.

Runtime performance also stays unchanged in Stage 1. Multi-field value classes and value objects compile to boxed reference classes on the JVM and Android right now. The current phase focuses on shallow immutability and identity-free semantics, while binary-compatible JVM optimizations wait for Project Valhalla (and closed-world optimizations on Native and Wasm). For single-field, allocation-sensitive wrappers like Dp, Color, or typed IDs, @JvmInline value class remains the right choice.

The feature is experimental in 2.5.0-RC2 behind -Xfull-value-classes, so it belongs in sandbox modules and unit tests while the API and ergonomic update story settle.

SHARE ENTRYLinkedIn ↗X ↗Markdown / AI ↗
Discussions ardakazanci/blog-comments
● GiscusView discussions on GitHub ↗
⑂Reactions & comments/ Sign in with GitHub to react or join the discussion.
Notifications Newsletter · beehiiv
✓ Active channelSubscribe directly ↗
✉Get new posts by email/ Android, Kotlin, and Compose notes. Straight to your inbox.

SUBSCRIPTION CONFIG · EMAIL DISPATCH

Stay synced with new entries

Receive practical engineering notes on Android architecture, Kotlin, and Jetpack Compose whenever a new article is published.

channel = "email"spam = falseunsubscribe = "anytime"
K subscriber.propertiesEmail address