Configure Compiler Arguments
Solution 1:
After a few days of search and experimentation, I finally found a way to configure the compiler based on the build variant.
Here is what worked for me :
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'// Configure Kotlin compiler optimisations for releases
kotlinOptions {
freeCompilerArgs += [
'-Xno-param-assertions',
'-Xno-call-assertions',
'-Xno-receiver-assertions'
]
}
}
}
}
It seems like the documentation for the Gradle Kotlin Android plugin is not correct: while it says that the compiler can be configured by adding, for instance, the compileReleaseKotlin
closure for release builds, for Android you have to put a kotlinOptions
block in release
, as shown above.
Note that for a regular Kotlin project (without Android), the compileKotlin
block described in the documentation works as intented.
Hope it helps !
Edit Added -
prefix for arguments, as the compiler would silently ignore them otherwise.
Edit 2 Changed =
to +=
to avoid overwriting compiler options from other configurations.
Solution 2:
For anyone looking for quick info in 2020 on how to add a compiler arg to a Kotlin Android project (I needed it to enable the experimental serialization API), this is how I did it:
(app build.gradle file)
android {
...
compileOptions {
...
kotlin {
kotlinOptions {
freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn"
}
}
}
}
Android Studio doesn't provide those as suggestions.
Solution 3:
Kotlin compiler options for all build types should be specified in the android
closure. This is where Android Studio 4.1 places kotlinOptions { jvmTarget = '1.8' }
by default:
android {
...
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs += ['-Xno-param-assertions']
}
}
Compiler options for specific build type should be configured at the root level, wrapped in afterEvaluate
, because the task is only registered once the Android Gradle plugin creates specific build variant, which is only done at the afterEvaluate
phase:
afterEvaluate {
compileReleaseKotlin {
kotlinOptions {
freeCompilerArgs += ['-Xno-param-assertions']
}
}
}
Post a Comment for "Configure Compiler Arguments"