Accessing Kotlin extension functions from Java
To access Kotlin extension functions in Java, treat them as static methods. These are packaged in a class, named after the Kotlin file they belong to, with Kt
suffix. Given an extension function in StringExtensions.kt
:
You'd access it in Java in this manner:
Defining a custom naming convention for the calling class in Java
You can utilize Kotlin's @JvmName
annotation to define a custom class name for Java.
And in Java, you refer to DemoUtils
instead of StringExtensionsKt
.
Matching understandings between Kotlin and Java
In the generated Java class, the receiver type (the class being extended in Kotlin) appears as the first parameter of the associated static method.
This function in Java requires the String
object as the first parameter:
Borrowing Kotlin's awesome sauce in Java classes
Use static imports to leverage convenience in your Java classes, mimicking Kotlin's dot-syntax.
Java's nullability annotations keep Kotlin's null safety
Annotate parameters in Java with @NotNull
or @Nullable
. Kotlin respects these annotations. It informs the Kotlin compiler of nullability. Check this Kotlin function:
Java, remember that null
is a possibility:
Predictable patterns of generated classes
Kotlin creates classes for Java to use following an understandable convention. A MyExtensions.kt
file results in:
A convention you can trust unless @JvmName
is playing.
Kotlin to Java tricks
Experience enhancement by knowing these interoperability tricks:
- Use
@JvmOverloads
for functions with default params. @JvmStatic
helps you access methods from Java without an instance within companion objects.@JvmField
directly exposes fields with the same visibility in Java.
Was this article helpful?