Kotlin与Java对比

在前面的内容里,我们已经看到了Java与Kotlin的互操作的基本方式。为了更好的认识Java与Kotlin这两门语言,我们在这里给出一些基本功能,同时使用Java与Kotlin来实现的代码实例。通过横向对比,从中我们可以看出它们的异同。

(此处可整理成表格形式)

打印日志

  • Java
  1. System.out.print("Java");
  2. System.out.println("Java");
  • Kotlin
  1. print("Kotlin")
  2. println("Kotlin")

其实,Kotlin中的println函数是一个内联函数,它其实就是通过封装java.lang.System类的System.out.println来实现的。

  1. @kotlin.internal.InlineOnly
  2. public inline fun print(message: Any?) {
  3. System.out.print(message)
  4. }

常量与变量

  • Java
  1. String name = "KotlinVSJava";
  2. final String name = "KotlinVSJava";
  • Kotlin
  1. var name = "KotlinVSJava"
  2. val name = "KotlinVSJava"

null声明

  • Java
  1. String otherName;
  2. otherName = null;
  • Kotlin
  1. var otherName : String?
  2. otherName = null

空判断

  • Java
  1. if (text != null) {
  2. int length = text.length();
  3. }
  • Kotlin
  1. text?.let {
  2. val length = text.length
  3. }
  4. // 或者
  5. val length = text?.length

在Kotlin中,我们只使用一个问号安全调用符号就省去了Java中烦人的if - null 判断。

字符串拼接

  • Java
  1. String firstName = "Jack";
  2. String lastName = "Chen";
  3. String message = "My name is: " + firstName + " " + lastName;
  • Kotlin
  1. val firstName = "Jack"
  2. val lastName = "Chen"
  3. val message = "My name is: $firstName $lastName"

Kotlin中使用$${}(花括号里面是表达式的时候)占位符来实现字符串的拼接,这个比在Java中每次使用加号来拼接要方便许多。

换行

  • Java
  1. String text = "First Line\n" +
  2. "Second Line\n" +
  3. "Third Line";
  • Kotlin
  1. val text = """
  2. |First Line
  3. |Second Line
  4. |Third Line
  5. """.trimMargin()

三元表达式

  • Java
  1. String text = x > 5 ? "x > 5" : "x <= 5";
  • Kotlin
  1. val text = if (x > 5)
  2. "x > 5"
  3. else "x <= 5"

操作符

  • java
  1. final int andResult = a & b;
  2. final int orResult = a | b;
  3. final int xorResult = a ^ b;
  4. final int rightShift = a >> 2;
  5. final int leftShift = a << 2;
  • Kotlin
  1. val andResult = a and b
  2. val orResult = a or b
  3. val xorResult = a xor b
  4. val rightShift = a shr 2
  5. val leftShift = a shl 2

类型判断和转换(显式)

  • Java
  1. if (object instanceof Car) {
  2. }
  3. Car car = (Car) object;
  • Kotlin
  1. if (object is Car) {
  2. }
  3. var car = object as Car

类型判断和转换 (隐式)

  • Java
  1. if (object instanceof Car) {
  2. Car car = (Car) object;
  3. }
  • Kotlin
  1. if (object is Car) {
  2. var car = object // Kotlin智能转换
  3. }

Kotlin的类型系统具备一定的类型推断能力,这样也省去了不少在Java中类型转换的样板式代码。

Range区间

  • Java
  1. if (score >= 0 && score <= 300) { }
  • Kotlin
  1. if (score in 0..300) { }

更灵活的case语句

  • Java
  1. public String getGrade(int score) {
  2. String grade;
  3. switch (score) {
  4. case 10:
  5. case 9:
  6. grade = "A";
  7. break;
  8. case 8:
  9. case 7:
  10. case 6:
  11. grade = "B";
  12. break;
  13. case 5:
  14. case 4:
  15. grade = "C";
  16. break;
  17. case 3:
  18. case 2:
  19. case 1:
  20. grade = "D";
  21. break;
  22. default:
  23. grade = "E";
  24. }
  25. return grade;
  26. }
  • Kotlin
  1. fun getGrade(score: Int): String {
  2. var grade = when (score) {
  3. 9, 10 -> "A"
  4. in 6..8 -> "B"
  5. 4, 5 -> "C"
  6. in 1..3 -> "D"
  7. else -> "E"
  8. }
  9. return grade
  10. }

for循环

  • Java
  1. for (int i = 1; i <= 10 ; i++) { }
  2. for (int i = 1; i < 10 ; i++) { }
  3. for (int i = 10; i >= 0 ; i--) { }
  4. for (int i = 1; i <= 10 ; i+=2) { }
  5. for (int i = 10; i >= 0 ; i-=2) { }
  6. for (String item : collection) { }
  7. for (Map.Entry<String, String> entry: map.entrySet()) { }
  • Kotlin
  1. for (i in 1..10) { }
  2. for (i in 1 until 10) { }
  3. for (i in 10 downTo 0) { }
  4. for (i in 1..10 step 2) { }
  5. for (i in 10 downTo 1 step 2) { }
  6. for (item in collection) { }
  7. for ((key, value) in map) { }

更方便的集合操作

  • Java
  1. final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);
  2. final Map<Integer, String> map = new HashMap<Integer, String>();
  3. map.put(1, "Jack");
  4. map.put(2, "Ali");
  5. map.put(3, "Mindorks");
  • Kotlin
  1. val listOfNumber = listOf(1, 2, 3, 4)
  2. val map = mapOf(1 to "Jack", 2 to "Ali", 3 to "Mindorks")

遍历

  • Java
  1. // Java 7
  2. for (Car car : cars) {
  3. System.out.println(car.speed);
  4. }
  5. // Java 8+
  6. cars.forEach(car -> System.out.println(car.speed));
  7. // Java 7
  8. for (Car car : cars) {
  9. if (car.speed > 100) {
  10. System.out.println(car.speed);
  11. }
  12. }
  13. // Java 8+
  14. cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));
  • Kotlin
  1. cars.forEach {
  2. println(it.speed)
  3. }
  4. cars.filter { it.speed > 100 }
  5. .forEach { println(it.speed)}

方法(函数)定义

  • Java
  1. void doSomething() {
  2. // 实现
  3. }
  4. void doSomething(int... numbers) {
  5. // 实现
  6. }
  • Kotlin
  1. fun doSomething() {
  2. // 实现
  3. }
  4. fun doSomething(vararg numbers: Int) {
  5. // 实现
  6. }

带返回值的方法(函数)

  • Java
  1. int getScore() {
  2. // logic here
  3. return score;
  4. }
  • Kotlin
  1. fun getScore(): Int {
  2. // logic here
  3. return score
  4. }
  5. // 单表达式函数
  6. fun getScore(): Int = score

另外,Kotlin中的函数是可以直接传入函数参数,同时可以返回一个函数类型的。

constructor 构造器

  • Java
  1. public class Utils {
  2. private Utils() {
  3. // 外部无法来调用实例化
  4. }
  5. public static int getScore(int value) {
  6. return 2 * value;
  7. }
  8. }
  • Kotlin
  1. class Utils private constructor() {
  2. companion object {
  3. fun getScore(value: Int): Int {
  4. return 2 * value
  5. }
  6. }
  7. }
  8. // 或者直接声明一个object对象
  9. object Utils {
  10. fun getScore(value: Int): Int {
  11. return 2 * value
  12. }
  13. }

JavaBean与Kotlin数据类

这段Kotlin中的数据类的代码:

  1. data class Developer(val name: String, val age: Int)

对应下面这段Java实体类的代码:

  • Java
  1. public final class Developer {
  2. @NotNull
  3. private final String name;
  4. private final int age;
  5. @NotNull
  6. public final String getName() {
  7. return this.name;
  8. }
  9. public final int getAge() {
  10. return this.age;
  11. }
  12. public Developer(@NotNull String name, int age) {
  13. Intrinsics.checkParameterIsNotNull(name, "name");
  14. super();
  15. this.name = name;
  16. this.age = age;
  17. }
  18. @NotNull
  19. public final String component1() {
  20. return this.name;
  21. }
  22. public final int component2() {
  23. return this.age;
  24. }
  25. @NotNull
  26. public final Developer copy(@NotNull String name, int age) {
  27. Intrinsics.checkParameterIsNotNull(name, "name");
  28. return new Developer(name, age);
  29. }
  30. // $FF: synthetic method
  31. // $FF: bridge method
  32. @NotNull
  33. public static Developer copy$default(Developer var0, String var1, int var2, int var3, Object var4) {
  34. if((var3 & 1) != 0) {
  35. var1 = var0.name;
  36. }
  37. if((var3 & 2) != 0) {
  38. var2 = var0.age;
  39. }
  40. return var0.copy(var1, var2);
  41. }
  42. public String toString() {
  43. return "Developer(name=" + this.name + ", age=" + this.age + ")";
  44. }
  45. public int hashCode() {
  46. return (this.name != null?this.name.hashCode():0) * 31 + this.age;
  47. }
  48. public boolean equals(Object var1) {
  49. if(this != var1) {
  50. if(var1 instanceof Developer) {
  51. Developer var2 = (Developer)var1;
  52. if(Intrinsics.areEqual(this.name, var2.name) && this.age == var2.age) {
  53. return true;
  54. }
  55. }
  56. return false;
  57. } else {
  58. return true;
  59. }
  60. }
  61. }