在 Kotlin 中构建失败并出现异常错误

Build failed with an exception error in Kotlin

在 android 工作室更新我的 Kotlin 插件后出现此错误。

package com.example.test

fun main(args: Array<String>) {
    println("Hello world")
}

这是我收到的错误:

* Where:
Initialization script '/private/var/folders/bn/st769wd16nv1d5_wccw8_tm00000gn/T/Test_main__2.gradle' line: 27

* What went wrong:
A problem occurred configuring project ': app'.
> Could not create task ':app:Test.main()'.
   > SourceSet with name 'main' not found.

当我 运行 堆栈跟踪时,这是我得到的响应:

Caused by: org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':app:Test.main()'.

Caused by: org.gradle.api.UnknownDomainObjectException: SourceSet with name 'main' not found.

这是我的 build.gradle(应用程序)文件

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdkVersion 30
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.example.test"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.13.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

build.Gradle(测试)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = "1.4.20"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"
        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
}

我已经更新了所有依赖项,使缓存无效并重新启动,尝试删除我的 .idea 和 .gradle 文件夹,并创建了新项目,但问题仍然存在。

这表明您创建了一个 Android 项目,但是 Android 应用程序使用 Android 生命周期到 运行,而不是主生命周期。

如果你想执行纯 kotlin 代码,一种选择是使用文件 -> 新模块 -> Kotlin 向项目添加一个 kotlin 库,并在其中添加主要方法