I'm trying to configure Kotlin to work with Java 1.8 in my Android project. I've tried adding the compileKotlin block at the bottom of my build.gradle file, but I get an error if I do so.

The error that occurs is the following:

错误:(38,0)找不到参数的方法compileKotlin()

The project runs fine without this block. What am I missing? Here's the complete build.gradle file, it's pretty basic stuff:

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'


android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'


    defaultConfig {
        minSdkVersion 24
        targetSdkVersion 25
        versionCode 1
        versionName '1.0.0'

        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.google.android.support:wearable:2.0.2'
}

repositories {
    mavenCentral()
}

compileKotlin {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8

    kotlinOptions {
        jvmTarget = '1.8'
        apiVersion = '1.1'
        languageVersion = '1.1'
    }
}

推荐答案

你得到的错误意味着项目中没有compileKotlin个任务,这是Android项目所期望的.

Android项目中的Kotlin编译任务名称包含build variant个名称(这些名称由构建类型、产品风格和其他设置组合而成,看起来像debugreleaseUnitTest——任务分别是compileDebugKotlincompileReleaseUnitTestKotlin).没有compileKotlin任务,它通常是为普通Java+Kotlin项目中的main个源代码集创建的.

Most probably, you want to configure all Kotlin compilation tasks in the project, and to do that, you can apply the block as follows:

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8

    kotlinOptions {
        jvmTarget = '1.8'
        apiVersion = '1.1'
        languageVersion = '1.1'
    }
}

Kotlin相关问答推荐

如果一项工作失败,请继续在Kotlin 等待其他工作/子元素完成

如何让Gradle8+在编译Kotlin代码之前编译Groovy代码?然后把它们混合在一个项目中?

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

Kotlin 说不需要强制转换,但删除后会出现新警告

使用 Kotlin 的 Springboot 中缺少 ResponseEntity 正文属性

在 kotlin 中重载函数时,我在一些非常基本的代码上不断收到类型不匹配

禁用 Android 12 默认启动画面

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

Kotlin 方法重载

Android 在将 androidx 生物识别更新为 1.0.0-alpha04 后崩溃

从列表中的每个对象中 Select 属性

变量后的Android问号

Kotlin默认使用哪种排序?

Kotlin协程处理错误和实现

使用Dagger 2提供函数依赖性

大小写敏感性 Kotlin / ignoreCase

生成Kotlin类图

如何为 Java 调用者声明返回类型为void的 Kotlin Lambda?

Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么

Java的Kotlin:字段是否可以为空?