java与kotlin混合编程

  被java的NPE拆腾得怀疑人生,因而思考是否可以使用号称NPE安全的神语言kotlin,但又不能完全抛弃java,所以两者是否可以混编,特地尝试了一下,使用gradle成功搭建,同时实现两者互调。

项目结构

java与kotlin混合编程_第1张图片

HelloJava

package com.kidshelloworld.jk;

public class HelloJava {
	public static void main(String[] args) {
		System.out.println(new Person("hello", 30));
		System.out.println(new Human());
	}
}

Person

package com.kidshelloworld.jk;

public class Person {
	private String name;
	private int age;

	public Person() {
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
	}
}

HelloKotlin

package com.kidshelloworld.jk

fun main() {
    println(Person("xixi", 10))
    println(Human())
}

Human

package com.kidshelloworld.jk

class Human {
    var sex: Int = 1

    override fun toString(): String {
        return "Human(sex=$sex)"
    }


}

gradle.properties

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.61"
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'kotlin'

group 'com.kidshelloworld'
version '1.0.0-SNAPSHOT'

sourceCompatibility = 1.8
targetCompatibility = 1.8
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

compileJava {
    options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation" << "-Xlint:none" << "-parameters"
    options.fork = true
    options.forkOptions.executable = 'javac'
    options.incremental = true
}

sourceSets {
    main.java.srcDirs = ['src/main/java']
    main.kotlin.srcDirs = ['src/main/kotlin']
    main.resources.srcDirs = ['src/main/resources']
}

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.61"
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile "org.jetbrains.kotlin:kotlin-reflect:1.3.61"
    testCompile "org.jetbrains.kotlin:kotlin-test:1.3.61"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:1.3.61"
}

参考资料

1. kotlin using gradle

你可能感兴趣的:(java,kotlin)