Is there any documentation on Kotlin `external` fu...
# getting-started
t
Is there any documentation on Kotlin
external
functions? How do they work? Is there a Java equivalent?
k
So something like https://github.com/JetBrains/skiko/blob/master/skiko/src/commonMain/kotlin/org/jetbrains/skia/Canvas.kt that defines a bunch of
external
functions, that are implemented in C++ and accessed via the JNI bridge
Java’s equivalent is
native
t
🤯
Is it bad practice to implement an
external
function with... not a native function? I want to declare an
external
function in an API module, and then implement it in different ways in subsequent modules.
k
That would be
expect
and
actual
most likely
t
It's not a multiplatform thing where the function is declared in a common module and then the JVM/JS/other implementations are declared in their own module
k
image.png
t
Yeah, it's not a multiplatform thing. I'm working strictly in the JVM.
k
Hence, the use of
external
might not be relevant
p
Just use a ServiceLoader? Or even a plain ol’ interface?
g
If you just want to implement some functionality somewhere else but in still in kotlin, you could use the normal
interface
and “somewhere else” create a
class
that extends that
interface
.
k
If you're talking about package-level functions (i.e. interfaces are not relevant), and you're asking about something equivalent to the extern keyword in C++, then the Kotlin equivalent is... nothing. You just have to either
import
the function name or just use its fully qualified name (including package name) at the place where you use it. Kotlin will know about this function if it is in the classpath. So all you have to do, if you have a number of alternative jars containing alternative implementations of the function, is to include one of those jars in your classpath when you compile the Kotlin file that uses the function.
447 Views