您的位置:

Kotlin转Java代码的细节和注意点

一、数据类型转换

1、基本数据类型的转换


// Kotlin
val a: Double = 5.0
val b: Int = a.toInt()

// Java
double a = 5.0;
int b = (int) a;

2、数组类型的转换


// Kotlin
val a: IntArray = intArrayOf(1, 2, 3)
val b: Array<Integer> = a.toTypedArray()

// Java
int[] a = new int[]{1, 2, 3};
Integer[] b = Arrays.stream(a).boxed().toArray(Integer[]::new);

二、空安全

1、判空语法的转换


// Kotlin
val a: String? = null
if (a == null) {
    println("a is null")
}

// Java
String a = null;
if (a == null) {
    System.out.println("a is null");
}

2、非空断言的转换


// Kotlin
val a: String? = null
val b = a!!

// Java
String a = null;
String b = Objects.requireNonNull(a, "a is null");

三、Lambda表达式

1、Lambda表达式的转换


// Kotlin
val list = listOf(1, 2, 3)
list.filter { it > 1 }.map { it * 2 }

// Java
List<Integer> list = Arrays.asList(1, 2, 3);
list.stream().filter(i -> i > 1).map(i -> i * 2).collect(Collectors.toList());

2、扩展函数的转换


// Kotlin
fun String.toTitleCase(): String {
    return split(" ").joinToString(" ") { it.capitalize() }
}

// Java
public static String toTitleCase(String str) {
    return Arrays.stream(str.split(" ")).map(s -> s.substring(0, 1).toUpperCase() + s.substring(1)).collect(Collectors.joining(" "));
}

四、DSL语法

1、DSL语法的转换


// Kotlin
class Person {
    var name: String? = null
    var age: Int? = null
}

fun person(block: Person.() -> Unit): Person {
    val p = Person()
    p.block()
    return p
}

person {
    name = "Alice"
    age = 25
}

// Java
public class Person {
    private String name;
    private Integer age;

    public Person name(String name) {
        this.name = name;
        return this;
    }

    public Person age(Integer age) {
        this.age = age;
        return this;
    }
}

Person person = new Person()
        .name("Alice")
        .age(25);

2、Lambda参数的转换


// Kotlin
fun foo(block: (Int, String) -> Unit) {
    block(42, "hello")
}

foo { a, b ->
    println("a=$a, b=$b")
}

// Java
public void foo(BiConsumer<Integer, String> block) {
    block.accept(42, "hello");
}

foo((a, b) -> System.out.println("a=" + a + ", b=" + b));

五、拓展函数

1、拓展函数的转换


// Kotlin
fun String.hasSpaces(): Boolean {
    return find { it == ' ' } != null
}

// Java
public static boolean hasSpaces(String str) {
    return str.contains(" ");
}

String str = "hello world";
hasSpaces(str);

2、Kotlin原生函数的转换


// Kotlin
val list = listOf(1, 2, 3)
list.forEachIndexed { index, value ->
    println("index=$index, value=$value")
}

// Java
List<Integer> list = Arrays.asList(1, 2, 3);
IntStream.range(0, list.size()).forEach(i -> System.out.println("index=" + i + ", value=" + list.get(i)));