Search code examples
javakotlinkotlin-multiplatformkotlin-multiplatform-mobilekmm

KMM with Java sources in common (shared) module


As a platform limitation we can't use Java sources with Kotlin Multiplatform Mobile.

But if Kotlin is 100% compatible with Java, why can't we use Java with Kotlin Multiplatform Mobile? I mean use it not only in Android or JVM section only, but in common section with shared code. We could write iOS apps with Java :)


Solution

  • Kotlin/JVM is indeed interoperable with Java, however KMM has two targets: Native and Android. This means that in common code you can use only dependencies which can be compiled by both the Kotlin/JVM and the Kotlin/Native compiler.

    In your case, when trying to add a java dependency in your common code, Kotlin/Native will not know how to translate that to iOS.

    What you can do is abstract away the JVM parts with the expect/actual and give an implementation for the Kotlin/Native compiler which it can understand, but you won't be able to use any Java library as it is.