Skip to main content
An external function in Kotlin is a function declaration that delegates its implementation to a foreign language or runtime environment. It acts as a binding mechanism, instructing the Kotlin compiler that the actual execution logic will be resolved at runtime from an outside source, such as a compiled C/C++ library or a JavaScript module. It is the direct Kotlin equivalent of the native keyword in Java.

Syntax

The external modifier is placed before the fun keyword. Because the implementation exists outside the Kotlin source, the function declaration must not contain a body.
External functions can be declared as top-level functions, member functions within a class, or extension functions.

Technical Characteristics

  • No Body: An external function cannot have a block body { ... } or an expression body = .... Attempting to provide one results in a compilation error.
  • Property Accessors: The external modifier can be applied to property getters and setters. To target an accessor, the external modifier must be placed directly on the get or set keyword itself, rather than on the property declaration.
(Note: In Kotlin/JS, the external modifier can be applied directly to a property declaration, but such properties are strictly prohibited from having custom accessors declared.)
  • Visibility and Modifiers: external functions support standard visibility modifiers (private, internal, public) and can be combined with other modifiers like open or override when participating in inheritance hierarchies.

Platform-Specific Resolution

The mechanism by which the Kotlin compiler and runtime resolve the external function depends on the compilation target: Kotlin/JVM On the JVM, external functions rely on the Java Native Interface (JNI). The Kotlin compiler generates bytecode identical to a Java native method. The corresponding C or C++ implementation must follow JNI naming conventions (e.g., Java_com_example_NativeProcessor_processData) and the shared library containing the implementation must be loaded into the JVM memory space, typically using an init block:
Kotlin/JS In Kotlin/JS, the external modifier informs the compiler that the function is implemented in JavaScript. The compiler does not perform name mangling on external declarations, ensuring the Kotlin signature maps directly to the underlying JavaScript function. It is frequently combined with annotations like @JsModule and @JsNonModule to define the exact module resolution path.
Kotlin/Native For Kotlin/Native, external functions are resolved using the cinterop tool. The compiler parses C header files (.h) to generate Kotlin bindings, allowing the external Kotlin function to map directly to the statically or dynamically linked LLVM bitcode of the C/Objective-C implementation.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More