자바 에서 Kotlin 까지 의 변화 - 기본 버 전 (자바 기반 보기 에 적합)

7030 단어
몇몇 다른 규범
  • Kotlin 은 문장의 끝 에 ; 점 수 를 붙 일 필요 가 없다
  • Kotlin 의 변 수 는 초기 화 되 어야 하고 자바 는 필요 하지 않 습 니 다
  • Kotlin 변 수 는 Python
  • 과 유사 한 변수 유형 을 자동 으로 식별 할 수 있 습 니 다.
    1. 인쇄 방식
  • Java
  • System.out.print("Hello, World!");
    System.out.println("Hello, World!");
    
  • Kotlin
  • print("Hello, World!")
    println("Hello, World!")
    

    2. Variables 변수
  • Java
  • 不可变变量
    final int x;
    final int y = 1;
    可变变量
    int x;
    int y = 2;
    x = 3;
    y = 1;
    
  • Kotlin
  • 不可变变量
    val x: Int
    val y = 1
    可变变量
    var x: Int
    var y = 2
    x = 3
    y = 1 
    

    3. 빈 값 NULL 에 대하 여
  • Java
  • final String name = null;
    
    String lastName;
    lastName = null
    
    if(text != null){
      int length = text.length();
    }
    
  • Kotlin
  • val name: String? = null
    
    var lastName: String?
    lastName = null
    
    var firstName: String
    firstName = null // 编译错误
    
    val length = text?.length
    
    val length = text!!.length // NullPointerException if text == null
    

    4. String 문자열
  • Java
  • String name = "John";
    String lastName = "Smith";
    String text = "My name is: " + name + " " + lastName;
    String otherText = "My name is: " + name.substring(2);
    
    String text = "First Line
    " + "Second Line
    " + "Third Line";
  • Kotlin
  • val name = "John"
    val lastName = "Smith"
    val text = "My name is: $name $lastName"
    val otherText = "My name is: ${name.substring(2)}"
    
    val text = """
            |First Line
            |Second Line
            |Third Line
    """.trimMargin()
    

    5. 삼원 연산 자
  • Java
  • String text = x > 5 ? "x > 5" : "x <= 5";
    
  • Kotlin
  • val text = if (x > 5)  "x > 5"  else "x <= 5"
    

    6. 비트 조작
  • 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;
    
  • 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
    

    7.Is As In
  • Java
  • if(x instanceof Integer){ }
    
    final String text = (String) other;
    
    if(x >= 0 && x <= 10 ){}
    
  • Kotlin
  • 这里的is指代判断
    if (x is Int) { }
    
    这里的as是类型转换
    val text = other as String
    
    if (x in 0..10) { }
    

    8. 스마트 전환
  • Java
  • if(a instanceof String){
      final String result = ((String) a).substring(1);
    }
    
  • Kotlin
  • if (a is String) {
      val result = a.substring(1)
    }
    

    9.Switch/When
  • Java
  • final int x = // value;
    final String xResult;
    
    switch (x){
      case 0:
      case 11:
        xResult = "0 or 11";
        break;
      case 1:
      case 2:
        //...
      case 10:
        xResult = "from 1 to 10";
        break;
      default:
        if(x < 12 && x > 14) {
          xResult = "not from 12 to 14";
          break;
        }
    
        if(isOdd(x)) {
          xResult = "is odd";
          break;
        }
    
        xResult = "otherwise";
    }
    
    
    
    final int y = // value;
    final String yResult;
    
    if(isNegative(y)){
      yResult = "is Negative";
    } else if(isZero(y)){
      yResult = "is Zero";
    }else if(isOdd(y)){
      yResult = "is Odd";
    }else {
      yResult = "otherwise";
    }
    
  • Kotlin
  • val x = // value
    val xResult = when (x) {
      0, 11 -> "0 or 11"
      in 1..10 -> "from 1 to 10"
      !in 12..14 -> "not from 12 to 14"
      else -> if (isOdd(x)) { "is odd" } else { "otherwise" }
    }
    
    val y = // value
    val yResult = when {
      isNegative(y) -> "is Negative"
      isZero(y) -> "is Zero"
      isOdd(y) -> "is odd"
      else -> "otherwise"
    }
    

    10.For
  • Java
  • for (int i = 1; i < 11 ; i++) { }
    
    for (int i = 1; i < 11 ; i+=2) { }
    
    for (String item : collection) { }
    
    for (Map.Entry entry: map.entrySet()) { }
    
  • Kotlin
  • for (i in 1 until 11) { }
    
    for (i in 1..10 step 2) {}
    
    for (item in collection) {}
    for ((index, item) in collection.withIndex()) {}
    
    for ((key, value) in map) {}
    

    11. 집합 (리스트, 지도)
  • Java
  • final List numbers = Arrays.asList(1, 2, 3);
    
    final Map map = new HashMap();
    map.put(1, "One");
    map.put(2, "Two");
    map.put(3, "Three");
    
    
    // Java 9
    final List numbers = List.of(1, 2, 3);
    
    final Map map = Map.of(1, "One",
                                            2, "Two",
                                            3, "Three");
    
    
    for (int number : numbers) {
      System.out.println(number);
    }
    
    for (int number : numbers) {
      if(number > 5) {
        System.out.println(number);
      }
    }
    
    
    
    final Map> groups = new HashMap<>();
    for (int number : numbers) {
      if((number & 1) == 0){
        if(!groups.containsKey("even")){
          groups.put("even", new ArrayList<>());
        }
    
        groups.get("even").add(number);
        continue;
      }
    
      if(!groups.containsKey("odd")){
        groups.put("odd", new ArrayList<>());
      }
    
      groups.get("odd").add(number);
    }
    
    // or
    
    Map> groups = items.stream().collect(
      Collectors.groupingBy(item -> (item & 1) == 0 ? "even" : "odd")
    );
    
    
    final List evens = new ArrayList<>();
    final List odds = new ArrayList<>();
    for (int number : numbers){
      if ((number & 1) == 0) {
        evens.add(number);
      }else {
        odds.add(number);
      }
    }
    
    
    final List users = getUsers();
    
    Collections.sort(users, new Comparator(){
      public int compare(User user, User otherUser){
        return user.lastname.compareTo(otherUser.lastname);
      }
    });
    
    // or
    
    users.sort(Comparator.comparing(user -> user.lastname));
    
  • Kotlin
  • val numbers = listOf(1, 2, 3)
    
    val map = mapOf(1 to "One",
                    2 to "Two",
                    3 to "Three")
    
    
    
    numbers.forEach {
        println(it)
    }
    
    numbers.filter  { it > 5 }
           .forEach { println(it) }
    
    
    val groups = numbers.groupBy {
                    if (it and 1 == 0) "even" else "odd"
                 }
    
    
    val (evens, odds) = numbers.partition { it and 1 == 0 }
    
    
    val users = getUsers()
    users.sortedBy { it.lastname }
    

    좋은 웹페이지 즐겨찾기