Search code examples
androidapikotlinbuild.gradlekotlin-multiplatform

Is it possible to create a kotlin multiplatform project referencing the correct target of a common module?


If we would like to build a multiplatform project with Kotlin and we have a structure like this one:

common
android
  android1
  android2
backend
  api1
  api2

where in the common module we have 3 targets / presets:

  • jvm (with common code to all jvm based projects)
  • jvmAndroid (with common code to all jvm android projects, depends on jvm)
  • jvmApi (with common code to all jvm api projects, depends on jvm)

How can we properly configure our build.gradles files to depend only on the correct preset / target?

For example, if we would like to use the common module as a dependency in our other projects we need to use something like:

dependencies {
  implementation project(':common')
}

But, is it possible to use only the correct part of the common module? Something like this (for android 1 and 2)?

dependencies {
  implementation project(':common:jvmAndroid')
}

Otherwise when we use implementation project(':common') this will get all jvm presets / targets but some code will only make sense or work in the correct platform (in this case android or api).


Solution

  • We can use a strategy called disambiguating targets to achieve this goal.

    https://kotlinlang.org/docs/multiplatform-set-up-targets.html#distinguish-several-targets-for-one-platform

    We need to do something like:

    val commonAttribute = Attribute.of("com.example", String::class.java)
    
    jvm {
        attributes.attribute(commonAttribute, "nameOfYourTarget")
    }
    

    Both in the "client" and "server" side. In the same way.