不能从java模块调用kotlin模块

ges*_*all 6 android kotlin

我想在java中有一个Android应用程序,但在kotlin中有一个库模块.但是,当我尝试在手机中运行应用程序时,出现错误,说它无法找到我的Kotlin类.这是我的kotlin课程:

    package com.example.mylibrary

    import android.util.Log

    class A {
        fun helloWorld(){
            Log.d("Kotlin", "Hello World!")
        }
    }
Run Code Online (Sandbox Code Playgroud)

和我的kotlin模块的gradle文件:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
buildscript {
    ext.kotlin_version = '0.6.+'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
repositories {
    mavenCentral()
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要活动:

package com.example.uisample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.example.mylibrary.A;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        A obj = new A();
        obj.helloWorld();

    }

}
Run Code Online (Sandbox Code Playgroud)

注意android studio的导入方式com.example.mylibrary.A而不是com.example.mylibrar.Akt参考文献.Android studio在编译之前没有报告任何错误.

应用程序的Gradle文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.example.uisample"
        minSdkVersion 11
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile project(':mylibrary')
}
Run Code Online (Sandbox Code Playgroud)

运行项目后,gradle抛出此错误:"找不到符号类A".我究竟做错了什么?

Dou*_*son 12

一些东西:

  1. 将kotlin-android插件应用到库模块build.gradle(参见文档):

    apply plugin: 'kotlin-android'
    
    Run Code Online (Sandbox Code Playgroud)

    就像现在一样,你甚至没有告诉gradle编译Kotlin文件.

  2. 您的buildscript块可能应该位于顶级build.gradle而不是模块build.gradle.

  3. 考虑更新完全发布的Kotlin 1.0.1-2版本