A private property in Kotlin is a class member or top-level variable declared with theDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
private visibility modifier, strictly confining its lexical scope and accessibility to the exact enclosing declaration.
Syntax
Theprivate modifier precedes the val (read-only) or var (mutable) keyword:
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 theprotectedmodifier). - Top-Level (File Level): When declared outside of any class, the property is visible to all functions, classes, and objects defined within that specific
.ktfile, 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:- Field Generation: It generates a
privatebacking field. - Accessor Generation: Unlike public properties, the Kotlin compiler does not generate public
get()andset()methods. - 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 theprivate visibility of the property itself.
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 objectcan access the private properties of its enclosing class instances.
Master Kotlin with Deep Grasping Methodology!Learn More





