A top-level property in Kotlin is a property declared directly at the root of aDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
.kt file, outside the scope of any class, interface, or object declaration. It is scoped to the package in which it is defined and is initialized when the file’s corresponding generated class is loaded by the ClassLoader.
Syntax
Top-level properties are declared using standardval (read-only) or var (mutable) keywords. They support explicit initialization, type inference, and custom accessors.
JVM Compilation Mechanics
Because the Java Virtual Machine (JVM) requires all fields and methods to be encapsulated within a class, the Kotlin compiler generates a facade class to host top-level properties. By default, if the file is namedNetwork.kt, the compiler generates a public final class named NetworkKt.
The compilation behavior depends on the property declaration:
-
Standard
valandvar: The compiler generates aprivate staticbacking field. It then generates apublic static finalgetter method (and a setter method forvar) to control access to that field. -
const val: The compiler generates apublic static finalfield. No getter is generated. The value is inlined at the call site during compilation. -
Custom Accessors (without
fieldreference): The compiler generatespublic static finalgetter/setter methods but omits theprivate staticbacking field entirely.
Visibility Modifiers
Visibility modifiers applied to top-level properties dictate their accessibility across the codebase:public(default): The property is accessible from anywhere in the project.internal: The property is accessible from anywhere within the same compiled module.private: The property is accessible only within the specific.ktfile where it is declared. The generated static field and methods are markedprivatein the bytecode.protected: Not allowed on top-level declarations.
Java Interoperability
When accessing Kotlin top-level properties from Java code, developers must invoke the generated static accessors on the file’s facade class.Modifying Java Interoperability
You can alter how the JVM compiles top-level properties using annotations:@file:JvmName("CustomName"): Placed at the very top of the.ktfile (before the package declaration), this changes the name of the generated facade class.@JvmField: Instructs the compiler not to generate getters/setters, but instead expose the property as apublic staticfield.
Master Kotlin with Deep Grasping Methodology!Learn More





