How Compose Compiler infers stability and decide their types?

skydovesJaewoong Eum (skydoves)||6 min read

How Compose Compiler infers stability and decide their types?

Jetpack Compose uses a smart recomposition system to optimize UI updates. At the heart of this optimization is stability inference - the compiler's ability to determine whether a type's values can change over time. Understanding how the compiler reasons about stability is crucial for writing performant Compose code.

What is Stability?

In Compose, a type is considered stable if it meets these conditions:

  1. The result of equals() will always return the same result for the same two instances
  2. If a public property of the type changes, Composition will be notified
  3. All public properties are also stable types

Common examples:

  • Stable: Primitives (Int, String, Boolean), @Immutable data classes, function types
  • Unstable: Classes with var properties, mutable collections (MutableList, MutableMap)

The Stability Type System

The Compose compiler uses a sophisticated type system to track stability information during compilation. This is represented by the Stability sealed class:

sealed class Stability {
    class Certain(val stable: Boolean) : Stability()
    class Runtime(val declaration: IrClass) : Stability()
    class Unknown(val declaration: IrClass) : Stability()
    class Parameter(val parameter: IrTypeParameter) : Stability()
    class Combined(val elements: List<Stability>) : Stability()
}

Each variant represents a different level of certainty about stability:

1. Certain Stability

class Certain(val stable: Boolean) : Stability()

This represents types whose stability is known at compile-time with 100% certainty.

Examples:

  • Certain(stable = true):

    • Primitives: Int, Long, Float, Double, Boolean, Char, Byte, Short
    • String, Enum classes
    • Function types: () -> Unit, (Int) -> String
  • Certain(stable = false):

    • Classes with var properties: data class MutableUser(var name: String)
    • Mutable collections: MutableList<String>, MutableMap<String, Int>
    • Classes with unstable properties

This article continues for subscribers

Subscribe to Dove Letter for full access to 40+ deep-dive articles about Android and Kotlin development.

Become a Sponsor