https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

Tianyu Zhu

02/14/2023, 7:59 PM
Is there any documentation on Kotlin
external
functions? How do they work? Is there a Java equivalent?
k

Kirill Grouchnikov

02/14/2023, 8:00 PM
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

Tianyu Zhu

02/14/2023, 8:04 PM
🤯
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

Kirill Grouchnikov

02/14/2023, 8:10 PM
That would be
expect
and
actual
most likely
t

Tianyu Zhu

02/14/2023, 8:11 PM
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

Kirill Grouchnikov

02/14/2023, 8:12 PM
image.png
t

Tianyu Zhu

02/14/2023, 8:12 PM
Yeah, it's not a multiplatform thing. I'm working strictly in the JVM.
k

Kirill Grouchnikov

02/14/2023, 8:13 PM
Hence, the use of
external
might not be relevant
p

Paul Griffith

02/15/2023, 1:35 AM
Just use a ServiceLoader? Or even a plain ol’ interface?
g

Goetz Markgraf

02/15/2023, 6:33 AM
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

Klitos Kyriacou

02/15/2023, 9:04 AM
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.
351 Views