配置编译器参数

我正在寻找一种方法来配置Android应用程序项目的build.gradle文件中的Kotlin编译器参数。

我在Kotlin官方文档中看到,可以为每个构建风格(例如debug,release)配置编译器参数。

项目级的build.gradle

 buildscript { ext.kotlin_version = '1.1.51' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.0-rc1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } 

应用程序级别的build.gradle

 apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "com.myapp.myapplication" minSdkVersion 16 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } // The interesting part : configure the compileReleaseKotlin task // to include compiler arguments when building releases compileReleaseKotlin { kotlinOptions { freeCompilerArgs = [ 'Xno-param-assertions', 'Xno-call-assertions', 'Xno-receiver-assertions' ] } } dependencies { // The usual Android dependencies, omitted for brievety } 

在构建项目时,出现以下错误:

 Could not find method compileReleaseKotlin() for arguments [build_7b4e2sfm3830f9z4br95gfme2$_run_closure2@7ed96f28] on project ':app' of type org.gradle.api.Project. 

compileReleaseKotlin块是错位的,还是拼错? 虽然Android Studio给我提供了这个方法。

经过几天的搜索和实验,我终于找到了一种基于构建变体来配置编译器的方法。

这是什么对我有用:

 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' ] } } } } 

看起来Gradle Kotlin Android插件的文档是不正确的:虽然它说编译器可以通过添加例如compileReleaseKotlin封闭来进行配置,但是对于Android,您必须将kotlinOptions块放入release如上所示。

请注意,对于常规的Kotlin项目(不包括Android),文档中描述的compileKotlin块的工作原理如图所示。

希望它有帮助!