Kotlin KMM 'commonMain' dependencies: Running works, AndroidStudio shows errors

Viewed 620

I did set up a KMM project as described here: https://kotlinlang.org/docs/mobile/getting-started.html

And I want to put some shared classes in the commonMain module. The classes require some dependencies. So I add the dependencies as describes here: https://kotlinlang.org/docs/mobile/add-dependencies.html#dependency-on-a-library-used-in-specific-source-sets

shared/build.gradle.kts (shortened)

....
kotlin {
    android()
    ios {
        binaries {
            framework {
                baseName = "shared"
            }
        }
    }
    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-reflect:1.4.31")
            }
        }
...
        val androidMain by getting {
            dependencies {
            }
        }
....
        val iosMain by getting
        val iosTest by getting
    }
}
....

So I created this InjectManager Helper class which makes use of the kotlin-reflect library.

The problem:

AndroidStudio (4.1.3) cannot find the dependency when the class is placed in commonMain only when placed in androidMain. When I run the project - no errors - everything works. It is just how Android Studio sees it. InjectManager and InjectManager2 have identical code. In order to be able to use autocomplete etc. my current workflow is like this

  1. move the class to androidMain
  2. do code changes
  3. dragdrop back to commonMain.

InjectManager2 is only for show purposes on the screenshot.

enter image description here

1 Answers

I had the same issue. The app built and ran fine, but various errors were appearing in my .kt files & classes in the commonMain package. I was able to get rid of them by adding the corresponding import statements, even though they were not necessary when the code was not in the shared module.

E.g. one file had errors (unresolved reference) with a couple instances of ArrayList(), and the errors disappeared after adding an import for java.util.ArrayList

Related