Skip to main content
A custom getter in Kotlin is a user-defined accessor method attached to a property that overrides the compiler-generated default read implementation. It allows developers to execute arbitrary logic, compute values dynamically, or intercept access to a backing field whenever the property is read.

Syntax

A custom getter is declared immediately following the property declaration using the get() keyword. It can be written using either a block body or an expression body. Block Body Syntax:
Expression Body Syntax:

Core Mechanics

Implicit Invocation Custom getters are invoked implicitly using standard property access syntax (instance.propertyName). At the bytecode level, the Kotlin compiler translates this property access into a standard Java getter method call (e.g., getPropertyName()). The Backing Field (field) Kotlin properties do not inherently have memory allocated to them. A backing field is generated by the compiler only if the property uses the default implementation of at least one accessor, or if a custom accessor references it through the implicit field identifier.
  • With Backing Field: If the custom getter references field, the compiler allocates memory for the property. Properties that require a backing field must be initialized (either at the declaration site or within a constructor).
  • Without Backing Field: If the custom getter computes its return value entirely from other sources and never references field (and the property lacks a default setter), the compiler omits the backing field entirely. The property exists purely as an accessor method and cannot have an initializer.

Type Inference

If the property type can be inferred from the custom getter’s return type, the explicit type declaration on the property can be omitted. However, explicitly defining the property type is standard practice for API clarity.

Visibility and Modifiers

The visibility of a custom getter must always exactly match the visibility of the property itself. Unlike custom setters, you cannot apply a more restrictive visibility modifier (like private) to a getter while keeping the property public. If the property is annotated, the annotation can be specifically targeted at the getter using the @get: use-site target.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More