Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What are the advantages of Kotlin over Java?


Jun 01, 2021 Article blog


Table of contents


With the development of computer language, from the original C C++ Java and other initial languages, in recent years, began to popular some called modern programming languages, such as: Rust Go Kotlin and TypeScript The reasons for the popularity of modern languages are summarized in the following points:

  1. Getting started is easier
  2. Type inference
  3. The empty pointer is safe
  4. Built-in concurring support
  5. Reduce template code (simple)
  6. It is easier to manipulate collections
  7. Smarter garbage collection

The above may not be very complete, but to some extent summarizes the characteristics of modern languages, let's look at the advantages of Kotlin based on the comparison between Kotlin and Java

New object

new an object is one of the most commonly used operations in programming, let's start by looking at how new an object in Java

List<String> list =new ArrayList<String>();
list.add("hello world");

In Java we need to define a variable and then declare an example of ArrayList<String> with the new keyword so that we can use it.

But in Kotlin a new object is more concise.

var list:ArrayList<String> = ArrayList<String>()

Just omit the new keyword.

Type inference

For the Kotlin code, we can completely omit the : the type declaration that follows, because kotlin can infer itself.

val list = ArrayList<String>()

Do you think it's more concise? We're also more efficient at developing.

The empty pointer is safe

In Java variables, method parameters, and so on can be null but are not allowed by default in Kotlin and this enforced restriction makes it better to avoid empty pointer exceptions.

var list = ArrayList<String>()
list = null

Above the code, you will get an error prompt during compilation:

Null can not be a value of a non-null type ArrayList<String>

What if we really need null assignments? In Kotlin the developer is required to display the claim himself.

var list:Array<String>? = null

As shown above, just add ? after the type. Note, however, that we do not advocate this approach, and in actual development, ? will find that ? Most of it is used to be compatible with Java code.

attribute

We typically encapsulate data and processing of data into a class, and if there are private fields in the class, we also need to provide getter and setter methods to provide methods for accessing and modifying fields.

//Person.java
public  class Person {
  private String name;


  public String getName() {
    return name;
  }


  public void setName(String name) {
    this.name = name;
  }
}
//Main.java
public static void main(String[] args) {
  Person p = new Person();
  p.setName("张三");
  System.out.println(p.getName());
}

These are the People classes we implemented through Java and we define the name private field, along with getter and setter so that we can use it.

From the above code, you can see that we have written a lot of code to implement a name storage, and if a class has many fields, we will write more unnecessary getter and setter methods.

Now let's look at how to implement the above functionality in Kotlin

//Person.kt
class Person {
  var name:String = ""
}


//main.kt
fun main(){
  val p = Person()
  p.name = "张三"
  println(p.name)
}

Yes, it's as simple as that, and with just a few lines of code, you can do the same thing as Java because Kotlin can help us automatically generate template code like getter and setter saving us a lot of things, greatly improving our development efficiency, and making the whole code cleaner.

It is important to note here that if the field is declared by val only getter method is generated because val is non-modifiable and equivalent to the final modifier in Java and if the field is var the getter and setter methods can be generated at the same time, at which point the field can be assigned a value.

The data class

Kotlin simplicity is not just reflected in getter and setter but also in the data class. A data class is a data container that holds data.

A good declaration of a data class has not only private fields, getter and setter equals but also implementations of toString equals, and hashCode methods to print, compare, and store them better in map

Or take the Person class as an example, a qualified data class code is as follows:

public static  class Person {
  private String name;


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


  public String getName() {
    return name;
  }


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


  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;


    Person person = (Person) o;


    return Objects.equals(name, person.name);
  }


  @Override
  public int hashCode() {
    return name != null ? name.hashCode() : 0;
  }


  @Override
  public String toString() {
    return "Person{" +
      "name='" + name + '\'' +
      '}';
  }
}

If you look at our Java implementation, you need more than 30 lines of code to implement it. What would it be like if we used Kotlin

data class Person(val name: String) {}

With just one line of code, the above Java functionality is implemented, and the key here is a data modifier, which is not very sour.

Concurrent

Kotlin provides co-ops for concurrencies, which are lighter and cleaner than Java Thread and Executor those. Let's compare the basic implementations of concurring.

public static void main(String[] args) throws InterruptedException {
  new MyThread().start();
  System.out.println(Thread.currentThread().getName()+":main");
  //保证JVM存活
  Thread.sleep(1000);
}


private static class MyThread extends Thread{
  @Override
  public void run() {
    try {
      Thread.sleep(500);
      System.out.println(Thread.currentThread().getName()+":Thread");
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

Running the view output, we found that MyThread did not block main execution, which is concurrent.

main:main
Thread-0:Thread

Note, however, that Java uses two threads, one main and one Thread-0 With the same functionality, we now use kotlin to implement the following:

fun main(){
  runBlocking {
    launch {
      delay(500)
      println("${Thread.currentThread().name}:Thread")
    }
    println("${Thread.currentThread().name}:main")
  }
}

It's cleaner than Java and let's look at the printed output:

main:main
main:Thread

It is also the concept of co-processing proposed by kotlin that is implemented concurrently on the same thread, with less application overhead and higher efficiency for one thread. If we don't want it to execute on the main thread, we can do so by switching schedulers.

launch(Dispatchers.IO)

All you need to do is replace the launch of the code above with launch(Dispatchers.IO) so that the scheduler assigns us an IO thread pool to execute our code. If we use Java to implement it, we have to define the thread pool ourselves, and we have to commit Runnable and the whole code is very much.

main:main
DefaultDispatcher-worker-1:Thread

kotlin co-equation is very powerful and concise, through the above example, can not fully demonstrate its characteristics, the rest of the co-process context, scheduler, Flow, channel and other capabilities you can explore.

brief summary

From the above comparison, we should be able to see the characteristics and advantages of being a modern programming language, and we have not completely listed the useful features of Kotlin such as convenient collection operations, property delegates, extension functions and so on.

Source: www.toutiao.com/a6862537179189477901/

The above is W3Cschool编程狮 about Kotlin and Java compared to what advantages of the relevant introduction, I hope to help you.