Android: Personal experience of a programmer who has used Kotlin for 3 years

Why learn kotlin, isn't it good to learn Java?

Indeed, if it was in the past few years, I would not recommend kotlin to everyone, and I didn't even know about it.

But since the advent of kotlin, I have used it for several years. Now let’s talk about the feeling of using Kotlin

why learn

When I was looking for a job a few years ago, there was a company I liked, but at that time, the recruitment required Android development engineers to have a solid foundation in Kotlin. Although I could find other companies, I am more persistent and study Kotlin seriously. moon. Then I still haven’t entered that company (it’s full /(ㄒoㄒ)/~~)

insert image description here

So if you need to learn Kotlin, you must learn it for Android.

You need to know it before learning kotlin

In order to learn kotlin better, we must first know where its advantages are.

  1. After more than ten years of development, kotlin has a relatively mature language and environment. More and more companies use it to develop Android applications. In addition, it can also be used for multi-platform development.
  2. We all know that in order for a language to be widely used, in addition to being fast and easy to use, it also needs to have a good ecology. We can use Kotlin and the Java programming language together in applications. The interoperability brings It is more convenient to use.
  3. Kotlin uses less code and has better readability. At the same time, many language features can avoid common programming errors. More importantly, it is easy to learn and use, especially for people with Java programming foundation .

To answer the question at the beginning, do you still need to learn kotlin if you know java?

Then look at the collision between kotlin and java

1. Faster than java

As follows: Create 1000000 objects

public class JPerson {
    public JPerson(String name, Integer age, Integer sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    private String name ;
   private Integer age;
   private Integer sex ;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

}

Results of the
insert image description here

public class ReflectDemo {

    public static void main(String[] args) throws InterruptedException {
            int i =0;
            long start = System.currentTimeMillis();
            while (i<1000000){
                JPerson jPerson = new JPerson("zhangsan",1,1);
                i++ ;
            }
            long end = System.currentTimeMillis();
            System.out.println("java本次耗时:"+(end-start));

    }

}

data class KPerson(val name: String, val age: Int, val sex: Int)

fun main(args: Array<String>) {
        var i = 0
        val start = System.currentTimeMillis()
        while (i < 1000000) {
            val kPerson = KPerson("张三", 1, 1)
            i = i.inc()
        }
        val end = System.currentTimeMillis()
        println("kotlin本次耗时:${(end - start)}")

}


Results of the

insert image description here

2. More concise than java syntax, here are some simple examples

//Java
System.out.print("hello world"); 
System.out.println("hello world");
//Kotlin 省略 System.out
print("hello world") 
println("hello world")

//Java
String name = "hello world"; 
final String name = "hello world";
//Kotlin 自动类型推断
var name = "hello world" 
val name = "hello world"

//Java
if (text != null) {
    int length = text.length();
}
//Kotlin 省略if 判断以及括号,可以使用it代替text
text?.let {
    val length = it.length
}

//Java
String firstName = "Android"; 
String lastName = "Architect"; 
String message = "My name is: " + firstName + " " + lastName;
//Kotlin 直接使用插值运算符
val firstName = "Android" 
val lastName = "Architect" 
val message = "My name is: $firstName $lastName"

//Java
String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";
 
//Kotlin 写法更加优雅
val text = """
        |First Line
        |Second Line
        |Third Line
        """.trimMargin()

//Java
Car car = (Car) object;
//Kotlin 使用as 转换 而且转换后后续无需再次转换
var car = object as Car
car.name  // 可以直接使用car 属性

//Java
int score = // some score;
String grade;
switch (score) {
    case 10:
    case 9:
        grade = "Excellent";
        break;
    case 8:
    case 7:
    case 6:
        grade = "Good";
        break;
    case 5:
    case 4:
        grade = "OK";
        break;
    case 3:
    case 2:
    case 1:
        grade = "Fail";
        break;
    default:
        grade = "Fail";
}

//Kotlin
var score = // some score
var grade = when (score) {
    9, 10 -> "Excellent"
    in 6..8 -> "Good"
    4, 5 -> "OK"
    in 1..3 -> "Fail"
    else -> "Fail"
}

// labamda表达式 Java 8+
cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));
 
 
//Kotlin
cars.forEach {
    println(it.speed)
}
 
cars.filter { it.speed > 100 }
      .forEach { println(it.speed)}
 
//Java  静态方法,私有构造比较
public class Utils {
 
    private Utils() {
      // This utility class is not publicly instantiable
    }
 
    public static int getScore(int value) {
        return 2 * value;
    }
 
}
 
 
//Kotlin
class Utils private constructor() {
 
    companion object {
 
        fun getScore(value: Int): Int {
            return 2 * value
        }
 
    }
} 
// java 对象声明
public class JPerson {
    public JPerson(String name, Integer age, Integer sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    private String name ;
   private Integer age;
   private Integer sex ;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

}

// kotlin
data class KPerson(val name: String, val age: Int, val sex: Int)
     

3. Make it more secure than Java, able to statically detect common pitfalls. Such as: referencing a null pointer
insert image description here

4. Support coroutines. Make development easier

The following parallel code, if the serial execution takes 5s, the actual execution result only takes 2s, that is, the maximum time-consuming of a single task, the parallel code is simpler than java

Feelings with Kotlin

If you switch from java to kotlin, you may feel that the kotlin syntax is weird at the beginning. For example, there is no need to add a semicolon at the end of each line, but it is always added inexplicably. As a result, the idea prompt is gray, and then the semicolon is removed. Then there is a simple way of writing, it is easy to make the code look like a declaration method, but actually call a method. Coupled with the project pressure, it is easy to write half kotlin and half java code.

But after a long time, I gradually discovered that the simple writing method of kotlin will kill most of the java code. The company's project reconstruction is to replace java with kotlin, and the code is directly reduced by 75%, which is quite powerful. Therefore, kotlin is still a very good language, hurry up and learn it

How to learn Kotlin

Good question, here is a free introduction to kotlin coroutine advanced practical information

Table of contents

insert image description here

insert image description here

Chapter 1 Introduction to the Basics of Kotlin Coroutines

  • 1.1 What is a coroutine
  • 1.2 What is Job, Deferred, and coroutine scope
  • 1.3 Basic usage of Kotlin coroutines

insert image description here

Chapter 2 Preliminary Explanation of Key Knowledge Points of Kotlin Coroutine

  • 2.1 Coroutine Scheduler
  • 2.2 Coroutine context
  • 2.3 Coroutine startup mode
  • 2.4 Coroutine scope
  • 2.5 Suspend functions

insert image description here

Chapter 3 Exception Handling of Kotlin Coroutines

insert image description here

Chapter 4 Basic application of kotlin coroutines in Android

  • 4.1 Android uses kotlin coroutines
  • 4.2 Using coroutines in Activity and Framgent
  • 4.3 Using coroutines in ViewModel
  • 4.4 Using coroutines in other environments

insert image description here

Chapter 5 Network request encapsulation of kotlin coroutine

  • 5.1 Common environments for coroutines
  • 5.2 Encapsulation and use of coroutines under network requests
  • 5.3 Higher-order function approach
  • 5.4 Return value method of multi-state function
  • 5.5 Ways to return values ​​directly
    insert image description here

Chapter 6 In-depth kotlin coroutine principle (1)

  • 6.1 Huahuachangzi of suspend
  • 6.2 Hidden behind - Continuation
  • 6.3 Hope in the Village - SuspendLambda

insert image description here

Chapter 7 In-depth kotlin coroutine principle (2)

  • 7.1 The little secrets of coroutines
  • 7.2 The process of creating a coroutine
  • 7.3 Suspending and resuming coroutines
  • 7.4 Execution and state machine of coroutine

insert image description here

Chapter 8 Kotlin Jetpack in Action

  • 8.1 Start with a demo that worships a great god
  • 8.2 What is the experience of writing Gradle scripts in Kotlin?
  • 8.3 The Triple Realm of Kotlin Programming
  • 8.4 Kotlin Higher Order Functions
  • 8.5 Kotlin Generics
  • 8.6 Kotlin Extensions
  • 8.7 Kotlin delegates

insert image description here

Chapter 9 Kotlin + Coroutine + Retrofit + MVVM Elegantly Realizes Network Requests

  • 9.1 Project configuration
  • 9.2 Implementation ideas
  • 9.3 Coroutine implementation
  • 9.4 Coroutine + ViewModel + LiveData implementation
  • 9.5 Subsequent optimization
  • 9.6 Exception handling
  • 9.7 Update Retrofit 2.6.0

insert image description here

Guess you like

Origin blog.csdn.net/Misdirection_XG/article/details/132181561