android java kotlin可以混编吗

发布网友

我来回答

2个回答

热心网友

可以
不过互相调用需要注意的点比较多

热心网友

上代码,其实就是在gradle中加入kotlin的插件就好了.

首先是project 的gradle文件
buildscript {
ext.kotlin_version = "1.0.1" //加上这个,至于为什么是1.0.1待会解释
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-alpha4'//这个不用管

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
//加上这个⬆️
}
}

然后是mole的gradle文件
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' //加上插件
...
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
...
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" //加上库

}

上面那个kotlin-version指向的是jcenter仓库http://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-compiler/最新的版本
Demo

代码是在android中运行的

kotlin代码
data class Student(val name:String,val sex:Char,val age:Int,val course:Array<String>){

}

java调用代码
public void demo() {
Student[] students = new Student[]{
new Student("x1",'男',14,new String[]{"数学","语文"}),
new Student("x2",'女',15,new String[]{"英语","语文"}),
new Student("x3",'男',16,new String[]{"化学","语文"}),
new Student("x4",'女',17,new String[]{"物理","语文"}),
};
for (Student student : students) {
Log.v(TAG,student.toString());
}
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com