1. Introduction

Earlier this year, Oracle filed another lawsuit against Google for up to $9 billion for allegedly infringing android’s use of Java. It was then revealed that Google was planning to switch its main language to Apple-led Swift, but this was never followed up.

But Google announced something new at the two-day I/O conference: Kotlin has officially become a tier 1 programming language for Android development. Kotlin, developed by JetBrains, was first launched in 2010 and open-source the following year, according to the document. It works 100% with Java and has many new features that Java doesn’t yet support, which will be available in the next release of Android Studio (3.0).

At the end of last year, I got in touch with Kotlin and tried to convert a prototype Android project from Java to Kotlin implementation and wrote an article (my first attempt to implement Android project with Kotlin). Now that Google is officially speaking, as an Android developer, not to mention whether to replace Java, it must be right to use spare time to learn systematically.

Various introductions and tutorials on Kotlin are available online, with a few links below:

English website

Chinese Version PDF Download

Kotlin in Chinese

Kotlin website Kotlin official website: Chinese

Kotlin for Android Developers

How to evaluate Kotlin language? – zhihu

Why Kotlin is Worth a try

 

2. The simplicity

Google was interested in moving from Java to Kotlin, not only because of the Oracle lawsuit, but also because Kotlin was developed by JetBrains. It’s not hard to guess that Kotlin itself has more than a few advantages over Java.

If you just want to experience the basic differences between Kotlin and Java, you can choose Intellij IDEA. It is faster to create and compile Java or Kotlin projects. If you need to write Kotlin code in an Android project, Android Studio is recommended, and while Kotlin is currently only supported as a plug-in, it works perfectly. So, if your computer allows, install both development environments in case you need them.

This article mainly compares several differences between Kotlin and Java by testing the code, and uses IntelliJ IDEA to build a Kotlin project Kotlin0. After that, the project about pure Kotlin code will be put in the address KotlinForJava on Github. Android projects involving Kotlin code implementations will be placed in Kotlin for Android.

No matter how well a tutorial is written, you can only learn superficial knowledge without continuous accumulation of code. In addition, The Kotlin website provides an online coding test, where those who are too lazy to build an environment can write code and run it directly.

2.1 Data class definition

Java:

 1 public class Artist {
 2     private long id;
 3     private String name;
 4     private String blog;
 5 
 6     public long getId() {
 7         return id;
 8     }
 9 
10     public void setId(long id) {
11         this.id = id;
12     }
13 
14     public String getName() {
15         return name;
16     }
17 
18     public void setName(String name) {
19         this.name = name;
20     }
21 
22     public String getBlog() {
23         return blog;
24     }
25 
26     public void setBlog(String blog) {
27         this.blog = blog;
28     }
29 
30     @Override public String toString() {
31         return "Artist{" +
32                 "id=" + id +
33                 ", name='" + name + '\ '' +
34                 ", blog='" + blog + '\ '' '}';
35     }
36 }Copy the code

Property + set + get +toString(), the basic function of a data class has three properties of the class to write more than thirty lines of code.

Kotlin:

1 data class Artist(
2         var id: Long,
3         var name: String,
4         var blog: String)Copy the code

In the above class definition, Kotlin uses the default access modifier public when declaring attributes, whereas Java is private. If Kotlin were private, it would also have to define a series of sets ()/get(), otherwise it would not be possible to get attributes from objects outside the class.

In addition to the amount of code you have to pay attention to the data keyword and the property list immediately following the class name.

Start with the argument list, which actually corresponds to the Parameter constructor in Java. If Kotlin defines a class with a list of parameters, it must pass in parameter values when creating a new object, unlike Java, which has two ways (1). 2 Create objects directly from the parameter list. But as you’ll see, Kotlin’s approach is much cleaner and safer than creating new objects without assigning attributes. Of course, Kotlin can still define other methods of construction, initialization, and general functionality.

Create an object

Java:

1 Artist artist = new Artist(1."Dylan"."http://www.cnblogs.com/tgyf/");Copy the code

Kotlin:

1 var artist = Artist(1."Dylan"."http://www.cnblogs.com/tgyf/")Copy the code

Kotlin objects are created without the new keyword, and statements are not followed by a semicolon “;” (Even if it is added, it will be ignored).

toString()

ToString (); toString(); toString(); toString();

1 println("artist.toString(): " + artist.toString())Copy the code

Result without data:

artist.toString(): Artist@61bbe9ba

Add the data result:

artist.toString(): Artist(id=1, name=Dylan, blog=http://www.cnblogs.com/tgyf/)

As you can see, toString() is generated automatically by Kotlin. If the class declaration does not include data, it simply prints a string of numbers (presumably the memory address of the class), not the property information of the current object.

2.2 Variable null security

Whether it is C++ Pointers or Java references, we are plagued by the problem of pointing to objects that are null. Kotlin provides a security mechanism that minimizes situations where variables are null before they are used.

Java:

1 String str;
2 if(str ! =null) {
3     //do something
4 }Copy the code

For Java code, the compiler does not enforce null judgments every time a reference variable is used, meaning exceptions tend to be reported at run time, but that’s where the danger lies.

Kotlin:

1 var str1: String = null  //Null can not be a value of a non-null type String
2 var str2: String? = null  //str2 can be null
3 var str3 = "testNull"  //non-null--String type
4 var str4 = null  //null
5 var str5: String  //non-null--String type
6 str5 = "testNull"  //assigned String value
7 var str6  //no type or initialization
8 var str7: String? = "testNull"Copy the code

With the comments in the code, let’s look at what these four lines of code mean.

In line 1, compilation error, Kotlin specifies that if str1 is explicitly specified, in this case String, the declaration must also specify whether null values are allowed without a question mark “?” The value cannot be NULL.

Line 2, which compiles, does another case of the first line, adds a question mark and assigns it to null;

On line 3, Kotlin will automatically infer that str3 is of type String and cannot be changed after that, that is, it cannot be assigned 1.

In line 4, the compiler passes, and the implicit assignment is null, so str4 will always be null;

Lines 5-6, which compile, just specify the type, no assignment; The latter gives str5 String values “testNull” and cannot be assigned to other types;

The compiler does not know what type STR6 is and cannot allocate space for it.

Line 8, without further explanation, str7 can be null and is also assigned to “testNull”;

Note: this article for the sake of uniform format, there is no compilation or running error code comments, shared project code is normal compilation and running.

Having explained the concept of emptiness in variable definitions, it’s time to see if this protection mechanism really saves us a lot of worry. For example, to get the length of a String, the Kotlin String class has a length property called strobject.length.

Variables defined in two forms need not be worried (1 is of type String and cannot be null; Class 2 does not include the length attribute), the reason is simple, the former does not have a null exception, the latter gets the length attribute error at compile time, or at the end of the code will be marked red. So, strings that are allowed to be null need our attention because of the potential for runtime exceptions.

For a String? The question mark and double exclamation point operators (“?”) are used to access properties. And “!!!!!” ), the former means checking the variable assignment before executing the following code, and the latter means accessing the attribute without checking it (dangerous).

The best way to understand this is to let the code do the talking.

 1 var str2: String? = null
 2 println("str2.length: " + str2.length)  //compile error
 3 println("str2? .length:"+ str2? .length)//print null
 4 println("str2!! .length:"+ str2!! .length)//run exception
 5 if(str2 ! =null) {
 6     println("str2!! .length:"+ str2!! .length)//don't run
 7 }
 8 str2 = "testNull"  //assign
 9 println("str2.length: " + str2.length)  //print 8
10 println("str2? .length:"+ str2? .length)//print 8
11 println("str2!! .length:"+ str2!! .length)//print 8
12 if(str2 ! =null) {
13     println("str2!! .length:" + str2.length)  //print 8
14 }Copy the code

Error: str2 is declared to be null and assigned to null, so access to its length property is not allowed.

In line 3, “null” is printed. If the question mark is added, the assignment of str2 will be checked first. If it is null, the last part (.length) will be returned.

In line 4, an exception is run and the consequence of not checking is to access the length property via a null reference;

Lines 5-7 are not executed in the if block, which is similar to what we do in Java;

At line 9, it prints “8”. At this point, rather than seeing Kotlin’s genius, after the assignment to str2 on line 8, it does not report a compile error like in line 2;

Lines 10-14, unexplained, non-null STR2, can access the Length property in all three ways;

So here’s a question, use “!!” It’s not a smart choice to access properties like “?” More secure? The latter, after all, can be handled if the variable is null or not. All I can think of is “!!” One of the scenarios is when a variable cannot be initialized immediately when it is declared but must be non-null when it is actually used. It’s not uncommon for this to happen. It comes in handy.

To start with a simple and crude example:

1 var str: String? = null
2 //do something to assign str
3 val str2: String = str!!Copy the code

If str2 is not null, it must be STR!! In order to compile.

The Application class singleton code in Android is given below without explanation.

 1 class App : Application() {
 2     companion object {
 3         private var instance: Application? = null
 4         fun instance() = instance!!
 5     }
 6     override fun onCreate() {
 7         super.onCreate()
 8         instance = this
 9     }
10 }Copy the code

2.3 Class method extension

This feature allows you to extend methods from existing classes, especially classes in the system library, because if you’re customizing a class, there’s no difference between extending and adding methods.

Method definition

1 fun getArtict(): Artist? {
2     return null
3 }Copy the code

In Kotlin, methods are declared with the fun keyword. If there is no return value, there is no need to write any type after the method name. The default is Unit.

extension

1 fun String.printStr() {
2     println("printStr: " + this)
3 }
4 
5 var str = "testExtend"
6 str.printStr()Copy the code

The code above extends printStr() for the String class, which is not possible in Java. Because in Java, if you can’t change an existing class and want to add methods to it, you have to create a new class to inherit. The reality is that there is only single inheritance in Java, which is a precious opportunity, and some classes are still uninheritable.

The result of line 5-6 of the code is:

printStr: testExtend

As you can see, the value of the object (caller) is obtained with the this keyword.

2.4 Lambda Expressions

This part of the test code is not in the shared project, because it involves Android development and needs to be compiled or run in the Android project, you can refer to this article.

The following to bind control, set button click event listening, click to change the text display as an example.

Java:

1 Button button = (Button) findViewById(R.id.button);
2 TextView text = (TextView) findViewById(R.id.text);
3 button.setOnClickListener(new View.OnClickListener() {
4 
5     @Override
6     public void onClick(View v) {
7         text.setText("Set text after click button");
8     }
9 });Copy the code

Android developers are familiar with this code, and while there are many open source libraries such as ButterKnife that can quickly bind without using findViewById(), you still need to manually bind.

Kotlin:

1 button.setOnClickListener {
2     text.setText("Set text after click button")
3     text.text = "Set text after click button"
4 }Copy the code

Button ~ r.ida button, the first text~ R.ida text, the second text~TextView display text. Lines 2-3 are the two ways to set the text. Kotlin recommends the second, more concise.text, which is why the data class attributes are defined at the beginning of this article with the default access modification, because the private attributes cannot be obtained directly through “.”.

What if multiple buttons need to share an onClick()? Instead of the Java code, let’s look at Kotlin:

 1 button1.setOnClickListener(this)
 2 button2.setOnClickListener(this)
 3 button3.setOnClickListener(this)
 4 
 5 override fun onClick(view: View) {
 6     val id = view.id
 7     when (id) {
 8         R.id.button1 -> selectImageBtn()
 9         R.id.button2 -> clearImageBtn()
10         R.id.button3 -> sendBulletinBtn()
11         else ->{}12     }
13 }Copy the code

In lines 1-3, setting up event listeners is similar to Java, except that you don’t need to call findViewById() to get the control;

In line 5-13, rewrite the keyword override without the “@” sign before it. Replace the original switch, case, and default with a combination of when, ->, and else. No longer need to write break at the end of each case.

 

3. Summary

This article mainly introduces Kotlin, gives the current better learning resources, through data class definition, variable empty safety, class method extension and lambda expression four aspects to do a simple comparison with Java, along with some other Kotlin basic knowledge. This is an introduction to Kotlin, and I will systematically study it later, and practice and summarize it based on the Android project.

The above is just a snapshot of What Kotlin has learned. For more on configuring your environment in Android development and further converting from Java to Kotlin, see this article.

One final note, and one that must be made clear when developing an Android application with Kotlin: Kotlin is based on the JVM. That is, it runs in the same JVM as Java, even though it is much cleaner coded than Java and makes development much more efficient. What’s more, Kotlin and Java are 100 percent compatible, meaning that their code can coexist and interact in a project.

Don’t let youth leave too many regrets, focus
Classification: Android, Java, Kotlin
Tags: Kotlin, Android, Java, Simplicity
Good writing is the best
Pay attention to my
Collect the paper

Footprints on the road



Attention – 3



Fans – 81.

+ add attention

5
0

The «The last:
Open source library RxJava, ButterKnife



» Next up:
Kotlin enters Class 2: Set Operations