Kotlin external Keyword
External calls
In Kotlin, the external keyword is used to declare functions or classes that are not written directly in Kotlin code but are implemented in another language. Because Kotlin generally runs on the JVM, the external keyword is mainly used for interaction with Java.
The external keyword indicates that the body of a function or class is not included in Kotlin code and is provided externally. For example, you can use the external keyword when calling Java methods or classes from Kotlin, or when calling Kotlin methods or classes from Java code.
The external keyword is commonly used when declaring native methods, when calling code written in C or C++ through JNI (Java Native Interface), or when calling JavaScript code. This allows Kotlin code to access and interact with external native code.
The simple form is as follows.
external fun foo (...) {...}
The following is a simple example of using the external keyword in Kotlin to interact with JNI.
external fun nativeMethod(): Int
fun main() {
val result = nativeMethod()
println("Result from native method: $result")
}
In the code above, nativeMethod() is not implemented directly in Kotlin code and is provided externally. This method is expected to be provided by native code written in C or C++ through JNI.