A public function in Kotlin is a subroutine accessible from any code that has visibility of its declaring scope, representing the least restrictive access level in Kotlin’s visibility modifier system. By default, all functions in Kotlin are implicitlyDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
public unless explicitly restricted using private, protected, or internal modifiers.
Syntax and Declaration
Becausepublic is the default visibility modifier, explicitly writing the public keyword is syntactically valid but considered redundant in idiomatic Kotlin. While the Kotlin compiler (kotlinc) accepts the explicit modifier without emitting warnings, modern IDEs will typically flag it with a redundancy inspection.
Scope Resolution
The accessibility of a public function depends entirely on its declaration context:- Top-Level Functions: A public function declared directly within a file (outside of any class or interface) is accessible from anywhere in the project, provided the caller imports the function’s package.
- Member Functions: A public function declared inside a class, interface, or object is accessible to any client code that holds a valid reference to an instance of that enclosing type. The actual accessibility is bounded by the visibility of the enclosing class (e.g., a public function inside a
privateclass is only accessible where theprivateclass is visible).
Inheritance and Overriding
When overriding a public function from a superclass or interface, the overriding function inherits thepublic visibility. Kotlin’s compiler enforces that you cannot reduce the visibility of an overridden member; a public function cannot be overridden as private, protected, or internal.
JVM Compilation Behavior
When targeting the Java Virtual Machine (JVM), Kotlin’spublic modifier maps directly to the Java public access modifier at the bytecode level.
- Member functions compile to standard
publicinstance methods. - Top-level public functions are compiled into
public staticmethods. The Kotlin compiler generates a file facade class named after the file (e.g.,UtilsKt.classforUtils.kt) to host these static methods. This generated class explicitly lacks theACC_SYNTHETICbytecode flag, ensuring it remains a standard, visible class that Java callers can access for seamless interoperability.
Master Kotlin with Deep Grasping Methodology!Learn More





