Search code examples
androidandroid-studiokotlingradlecompiler-options

Use Kotlin compiler options for test sources in Android Studio


In my test sources I want to use some experimental Kotlin compiler feature to not see the lint warnings and errors for them in Android Studio. For example, I want to apply the following Kotlin options to all test sources.

compileTestKotlin {
  kotlinOptions {
    freeCompilerArgs += [
        '-Xopt-in=kotlin.time.ExperimentalTime',
        '-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
    ]
  }
}

(source)

Out of the box this doesn't work in an Android project, because there is no compileTestKotlin method. According to the kotlin-android Gradle plugin docs, it should be possible to do this for compileVariantNameKotlin in an afterEvaluate block, e.g.:

afterEvaluate {
  compileDebugUnitTestKotlin {
    kotlinOptions {
      freeCompilerArgs += [
        '-Xopt-in=kotlin.time.ExperimentalTime',
        '-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
      ]
    }
  }
}

(and similar for compileReleaseUnitTestKotlin)

Although this works (builds and test run and pass just fine), there seems to be no effect in Android Studio: usages of the experimental compiler features are still marked with warnings/errors.

How do I enable these compiler features for my test sources in such a way that AS recognizes and uses them?


Solution

  • This worked for me on Android Studio 4.2.2, AGP version 4.2.0, Kotlin version 1.5.10:

    android {
        testOptions {
            kotlinOptions {
                freeCompilerArgs += [
                    '-Xopt-in=kotlin.time.ExperimentalTime',
                    '-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi',
                ]
            }
        }
    }