Interop with Java, Swift and Objective-C

Article · 2:00

Platform types, the annotations that shape the generated API, and where interop leaks.

Kotlin's null safety stops at the boundary of code it did not compile. A value returned from Java has a platform type, written String! in error messages, which the compiler neither trusts as non-null nor forces you to check. This is a pragmatic compromise - requiring a null check on every Java call would make interop unusable - and it means the one place a NullPointerException can still appear is immediately after a Java call. Annotate the Java side with @Nullable and @NotNull, or check at the boundary.

Several annotations shape what Java sees. @JvmStatic generates a real static method rather than requiring Companion. @JvmOverloads generates the overload family that Java needs because it has no default arguments. @JvmName renames a function, which also resolves the signature clashes that type erasure creates. @Throws declares a checked exception so Java callers can catch it.

Going the other way, Kotlin/Native generates an Objective-C header that Swift consumes. The translation is lossy in ways worth anticipating: suspend functions become completion handlers or Swift async functions; sealed hierarchies lose exhaustiveness, so a Swift switch still needs a default; generics are weakened; and default arguments disappear. The usual advice is to design the public multiplatform surface as a small, flat, Swift-friendly API rather than exposing idiomatic Kotlin directly.

class Analytics {

    // Java sees three overloads instead of one method with defaults
    @JvmOverloads
    fun track(event: String, value: Int = 0, urgent: Boolean = false) {
        println("$event / $value / $urgent")
    }

    companion object {
        // Without @JvmStatic, Java must write Analytics.Companion.create()
        @JvmStatic
        fun create(): Analytics = Analytics()

        @JvmName("parseStrings")
        fun parse(items: List<String>): Int = items.size
    }
}

// A value from Java arrives as a platform type: not checked, not trusted.
// Checking at the boundary is the only way to keep null safety meaningful.
fun handle(fromJava: String?) {
    val safe = fromJava ?: return
    println(safe.uppercase())
}

fun main() {
    Analytics.create().track("app_open")
    handle(null)
    handle("ok")
}

Discussion

No questions on this topic yet. Sign in to ask the first one.