Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A private property in Kotlin is a class member or top-level variable declared with the private visibility modifier, strictly confining its lexical scope and accessibility to the exact enclosing declaration.

Syntax

The private modifier precedes the val (read-only) or var (mutable) keyword:
private val immutableData: String = "Static"
private var mutableState: Int = 0

Scoping Rules

The exact boundary of a private property depends on its declaration context:
  • Class/Interface Level: When declared inside a class or interface, the property is visible only within the {} block of that specific class. It is strictly invisible to external classes, instantiating code, and subclasses (unlike the protected modifier).
  • Top-Level (File Level): When declared outside of any class, the property is visible to all functions, classes, and objects defined within that specific .kt file, but invisible to the rest of the module or package.

JVM Compilation and Backing Fields

Under the hood, when compiling to the JVM, Kotlin handles private properties differently than public ones:
  1. Field Generation: It generates a private backing field.
  2. Accessor Generation: Unlike public properties, the Kotlin compiler does not generate public get() and set() methods.
  3. Direct Access: Accessing the private property from within its allowed scope is typically optimized by the compiler into direct field access at the bytecode level, bypassing method invocation overhead unless custom accessors are defined.

Custom Accessors

Private properties fully support custom getters and setters. The accessors implicitly inherit the private visibility of the property itself.
class DataContainer {
    private var internalCounter: Int = 0
        get() = field + 1
        set(value) {
            field = if (value > 0) value else 0
        }
}

Companion Object Interaction

Kotlin enforces a specific visibility relationship between a class and its companion object regarding private members:
  • A class can access the private properties of its companion object.
  • A companion object can access the private properties of its enclosing class instances.
class OuterClass {
    private val instanceSecret = "Instance Level"

    companion object {
        private val staticSecret = "Companion Level"
    }

    fun readCompanion() {
        println(staticSecret) // Valid access
    }
}
Master Kotlin with Deep Grasping Methodology!Learn More