Kotlin backing field vs. backing property: when to use each

A backing field is the storage the Kotlin compiler generates for a property, accessed via the keyword field inside its getter or setter. A backing property is a separate private property written by the developer, typically when the stored value must have a different type than the exposed one. The article illustrates this with a common ViewModel pattern that pairs a private mutable state flow with a public read-only view. It also explains a frequent setter mistake that causes a StackOverflowError when a property is assigned to itself instead of field. Finally, it notes that Kotlin 2.4 introduced an explicit backing field declaration that handles the most common backing-property use case in a single declaration.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in