Java VS Kotlin:基础语法比较

向右看齐 2022-11-30 01:24 230阅读 0赞

在这里插入图片描述

转载自 https://github.com/MindorksOpenSource/from-java-to-kotlin

打印日志

  • Java

    System.out.print(“Amit Shekhar”);
    System.out.println(“Amit Shekhar”);

  • Kotlin

    print(“Amit Shekhar”)
    println(“Amit Shekhar”)


常量与变量

  • Java

    String name = “Amit Shekhar”;
    final String name = “Amit Shekhar”;

  • Kotlin

    var name = “Amit Shekhar”
    val name = “Amit Shekhar”


null声明

  • Java

    String otherName;
    otherName = null;

  • Kotlin

    var otherName : String?
    otherName = null


空判断

  • Java

    if (text != null) {

    1. int length = text.length();

    }

  • Kotlin

    text?.let {

    1. val length = text.length

    }
    // or simply
    val length = text?.length


字符串拼接

  • Java

    String firstName = “Amit”;
    String lastName = “Shekhar”;
    String message = “My name is: “ + firstName + “ “ + lastName;

  • Kotlin

    val firstName = “Amit”
    val lastName = “Shekhar”
    val message = “My name is: $firstName $lastName”


换行

  • Java

    String text = “First Line\n” +

    1. "Second Line\n" +
    2. "Third Line";
  • Kotlin

    val text = “”” |First Line |Second Line |Third Line “””.trimMargin()


三元表达式

  • Java

    String text = x > 5 ? “x > 5” : “x <= 5”;

  • Kotlin

    val text = if (x > 5)

    1. "x > 5"
    2. else "x <= 5"

操作符

  • java

    final int andResult = a & b;
    final int orResult = a | b;
    final int xorResult = a ^ b;
    final int rightShift = a >> 2;
    final int leftShift = a << 2;
    final int unsignedRightShift = a >>> 2;

  • Kotlin

    val andResult = a and b
    val orResult = a or b
    val xorResult = a xor b
    val rightShift = a shr 2
    val leftShift = a shl 2
    val unsignedRightShift = a ushr 2


类型判断和转换 (声明式)

  • Java

    if (object instanceof Car) {
    }
    Car car = (Car) object;

  • Kotlin

    if (object is Car) {
    }
    var car = object as Car


类型判断和转换 (隐式)

  • Java

    if (object instanceof Car) {
    Car car = (Car) object;
    }

  • Kotlin

    if (object is Car) {
    var car = object // 聪明的转换
    }


多重条件

  • Java

    if (score >= 0 && score <= 300) { }

  • Kotlin

    if (score in 0..300) { }


更灵活的case语句

  • Java

    int score = // some score;
    String grade;
    switch (score) {

    1. case 10:
    2. case 9:
    3. grade = "Excellent";
    4. break;
    5. case 8:
    6. case 7:
    7. case 6:
    8. grade = "Good";
    9. break;
    10. case 5:
    11. case 4:
    12. grade = "OK";
    13. break;
    14. case 3:
    15. case 2:
    16. case 1:
    17. grade = "Fail";
    18. break;
    19. default:
    20. grade = "Fail";

    }

  • Kotlin

    var score = // some score
    var grade = when (score) {

    1. 9, 10 -> "Excellent"
    2. in 6..8 -> "Good"
    3. 4, 5 -> "OK"
    4. in 1..3 -> "Fail"
    5. else -> "Fail"

    }


for循环

  • Java

    for (int i = 1; i <= 10 ; i++) { }

    for (int i = 1; i < 10 ; i++) { }

    for (int i = 10; i >= 0 ; i—) { }

    for (int i = 1; i <= 10 ; i+=2) { }

    for (int i = 10; i >= 0 ; i-=2) { }

    for (String item : collection) { }

    for (Map.Entry entry: map.entrySet()) { }

  • Kotlin

    for (i in 1..10) { }

    for (i in 1 until 10) { }

    for (i in 10 downTo 0) { }

    for (i in 1..10 step 2) { }

    for (i in 10 downTo 0 step 2) { }

    for (item in collection) { }

    for ((key, value) in map) { }


更方便的集合操作

  • Java

    final List listOfNumber = Arrays.asList(1, 2, 3, 4);

    final Map keyValue = new HashMap();
    map.put(1, “Amit”);
    map.put(2, “Ali”);
    map.put(3, “Mindorks”);

    // Java 9
    final List listOfNumber = List.of(1, 2, 3, 4);

    final Map keyValue = Map.of(1, “Amit”,

    1. 2, "Ali",
    2. 3, "Mindorks");
  • Kotlin

    val listOfNumber = listOf(1, 2, 3, 4)
    val keyValue = mapOf(1 to “Amit”,

    1. 2 to "Ali",
    2. 3 to "Mindorks")

遍历

  • Java

    // Java 7 and below
    for (Car car : cars) {
    System.out.println(car.speed);
    }

    // Java 8+
    cars.forEach(car -> System.out.println(car.speed));

    // Java 7 and below
    for (Car car : cars) {
    if (car.speed > 100) {

    1. System.out.println(car.speed);

    }
    }

    // Java 8+
    cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));

  • Kotlin

    cars.forEach {

    1. println(it.speed)

    }

    cars.filter { it.speed > 100 }

    1. .forEach { println(it.speed)}

方法定义

  • Java

    void doSomething() {
    // logic here
    }

    void doSomething(int… numbers) {
    // logic here
    }

  • Kotlin

    fun doSomething() {
    // logic here
    }

    fun doSomething(vararg numbers: Int) {
    // logic here
    }


带返回值的方法

  • Java

    int getScore() {
    // logic here
    return score;
    }

  • Kotlin

    fun getScore(): Int {
    // logic here
    return score
    }

    // as a single-expression function

    fun getScore(): Int = score


无结束符号

  • Java

    int getScore(int value) {

    1. // logic here
    2. return 2 * value;

    }

  • Kotlin

    fun getScore(value: Int): Int {
    // logic here
    return 2 * value
    }

    // as a single-expression function

    fun getScore(value: Int): Int = 2 * value


constructor 构造器

  • Java

    public class Utils {

    1. private Utils() {
    2. // This utility class is not publicly instantiable
    3. }
    4. public static int getScore(int value) {
    5. return 2 * value;
    6. }

    }

  • Kotlin

    class Utils private constructor() {

    1. companion object {
    2. fun getScore(value: Int): Int {
    3. return 2 * value
    4. }
    5. }

    }

    // another way

    object Utils {

    1. fun getScore(value: Int): Int {
    2. return 2 * value
    3. }

    }


Get Set 构造器

  • Java

    public class Developer {

    1. private String name;
    2. private int age;
    3. public Developer(String name, int age) {
    4. this.name = name;
    5. this.age = age;
    6. }
    7. public String getName() {
    8. return name;
    9. }
    10. public void setName(String name) {
    11. this.name = name;
    12. }
    13. public int getAge() {
    14. return age;
    15. }
    16. public void setAge(int age) {
    17. this.age = age;
    18. }
    19. @Override
    20. public boolean equals(Object o) {
    21. if (this == o) return true;
    22. if (o == null || getClass() != o.getClass()) return false;
    23. Developer developer = (Developer) o;
    24. if (age != developer.age) return false;
    25. return name != null ? name.equals(developer.name) : developer.name == null;
    26. }
    27. @Override
    28. public int hashCode() {
    29. int result = name != null ? name.hashCode() : 0;
    30. result = 31 * result + age;
    31. return result;
    32. }
    33. @Override
    34. public String toString() {
    35. return "Developer{" +
    36. "name='" + name + '\'' +
    37. ", age=" + age +
    38. '}';
    39. }

    }

  • Kotlin

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


原型扩展

  • Java

    public class Utils {

    1. private Utils() {
    2. // This utility class is not publicly instantiable
    3. }
    4. public static int triple(int value) {
    5. return 3 * value;
    6. }

    }

    int result = Utils.triple(3);

  • Kotlin

    fun Int.triple(): Int {
    return this * 3
    }

    var result = 3.triple()

  • Java

    public enum Direction {

    1. NORTH(1),
    2. SOUTH(2),
    3. WEST(3),
    4. EAST(4);
    5. int direction;
    6. Direction(int direction) {
    7. this.direction = direction;
    8. }
    9. public int getDirection() {
    10. return direction;
    11. }
    12. }
  • Kotlin

    enum class Direction(val direction: Int) {

    1. NORTH(1),
    2. SOUTH(2),
    3. WEST(3),
    4. EAST(4);

    }


发表评论

表情:
评论列表 (有 0 条评论,230人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Kotlin学习-基础语法

    写在前面 因为实验室需要,需要将原来的桌面应用程序改成安卓端的程序,所以正好使用kotlin进行开发。 主要内容 > 基础知识 Kotlin 是一种在 Java