Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the advantages of Kotlin over Java programming language?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the advantages of Kotlin versus Java programming language". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

New object

New an object is one of the most common operations we use in programming. Let's first look at how to new an object in Java.

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

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

But in Kotlin,new, an object is more concise.

Var list:ArrayList = ArrayList ()

Just omit the new keyword.

Type inference

For the above Kotlin code, we can omit the variable: the later type declaration, because kotlin can infer it itself.

Val list = ArrayList ()

Do you think it's more concise? Our development is also more efficient.

Null pointer security

In Java, variables, method parameters, etc., can be null, but it is not allowed by default in Kotlin. Through this mandatory restriction, null pointer exceptions can be better avoided.

Var list = ArrayList () list = null

For the above code, you will get an error prompt at compile time:

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

What if we do need null assignments? Developers are required to display their own statements in Kotlin.

Var list:Array? = null

As shown above, add after the type? That's it. But note that we do not advocate this approach, in the actual development, you will find? Most of them are used for compatibility with Java code.

Attribute

We usually encapsulate the data and the processing of the 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 to access and modify 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 ("Zhang San"); System.out.println (p.getName ());}

This is a Person class that we implemented through Java, with a name private field defined and getter and setter methods provided 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. If there are many fields in a class, we will write more unnecessary getter and setter methods.

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

/ / Person.kt class Person {var name:String = ""} / / main.kt fun main () {val p = Person () p.name = "Zhang San" println (p.name)}

Yes, it is that simple, only a few lines of code, and Java can achieve the same function, because Kotlin can help us automatically generate getter and setter these template code, save us a lot of things, greatly improve our development efficiency, and the whole code is more concise.

It is important to note that if the field is declared by val, only the getter method is generated, because val is immutable and is equivalent to the final modifier in Java; if the field is var, you can generate both getter and setter methods, and you can assign values to the field.

Data class

The simplicity of Kotlin is reflected not only in getter and setter methods, but also in data classes. A data class is a data container that is used to store data.

A good data class declaration includes not only private fields, getter and setter methods, but also implementations of toString, equals, and hashCode methods so that they can be printed, compared, and better stored 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 +'\'+'}';}}

Take a look at our implementation of Java, which requires more than 30 lines of code to implement. What would happen if we used Kotlin?

Data class Person (val name: String) {}

All the above Java functions will be implemented with this line of code, and the key here is whether a data modifier is sour or not.

Concurrence

Kotlin provides a cooperative program to achieve concurrency, which is lighter and simpler than Java's Thread and Executor. Let's compare the basic implementation of concurrency.

Public static void main (String [] args) throws InterruptedException {new MyThread (). Start (); System.out.println (Thread.currentThread (). GetName () + ": main"); / / guarantee JVM survival 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 ();}

When we run to see the output, we find that MyThread does not block the execution of main, that is, concurrency.

Main:main Thread-0:Thread

Note, however, that Java uses two threads, one main and one Thread-0. For the same function, we now use kotlin to implement:

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

It's more concise than Java, and let's take a look at the printed output:

Main:main main:Thread

It turns out that the concurrency is realized on the same thread, which reduces the application overhead of one thread and is more efficient, which is also the concept of cooperation program put forward by kotlin. If we don't want it to execute on the mainthread, we can do this by switching the scheduler.

Launch (Dispatchers.IO)

Just replace the launch of the above code with launch (Dispatchers.IO), so that the scheduler assigns us a thread pool of IO to execute our code. If we use Java to implement, define the thread pool ourselves, and submit the Runnable, there is a lot of code.

Main:main DefaultDispatcher-worker-1:Thread

The cooperation process of kotlin is very powerful and simple. Through the above examples, its features can not be fully demonstrated. You can explore the remaining capabilities such as context, scheduler, Flow, channel and so on.

This is the end of the introduction of "what are the advantages of Kotlin over the Java programming language". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report