What Android Developers should know about Kotlin

Source: Internet
Author: User

What Android Developers should know about Kotlin
Android Developers face a dilemma in terms of language restrictions. As we all know, the current Android development only supports Java 6 (the language itself has been improved since Java 7). Therefore, we can only use one old language for development every day, this greatly reduces our productivity and forces us to write a lot of samples and vulnerable code. However, such code is hard to read and maintain. Fortunately, Android programs run on java virtual machines. Therefore, technically, everything that can run on JVM can be used to develop Android applications. Now there are many languages that can generate bytecode that can be executed by JVM. Some of these languages have emerged and gradually become popular. Kotlin is one of the best among them.

What is Kotlin?

Kotlin is a language running on JVM. It was created by Jetbrains, and Jetbrains is behind many powerful tools (such as the well-known Java IDE IntelliJ IDEA. Kotlin is a very simple language. One of its main goals is to provide powerful languages while maintaining simple and simplified syntax. Its main features are as follows:

Lightweight: This is very important for Android. The library required by the project should be as small as possible. Android imposes strict restrictions on the number of methods. Kotlin only adds about 6000 methods. Interoperability: Kotlin can communicate seamlessly with Java. This means that we can use any existing Java library in the Kotlin code. Therefore, even if the language is still young, we can use hundreds of thousands of libraries. In addition, Kotlin code can also be used by Java code, which means we can use these two languages to build software. You can use Kotlin to develop new features and use Java to implement other parts of the code base. Strong type: We seldom need to specify the type in the code, because the compiler can deduce the type of the variable or function return value in most cases. This provides two benefits: simplicity and security. Null security: the biggest problem in Java is null. If no null judgment is made on the variables or parameters, a large number of NullPointerException may be thrown in the program, which is hard to be detected during encoding. Kotlin uses explicit null, which forces us to perform a null check if necessary.

Currently, the Kotlin version is 1.0.0 Beta 3, but the official version will be released soon. It can be used in production, and now many companies have successfully applied Kotlin.

Why is Kotlin very suitable for Android?

Basically, this is because all features of Kotlin are very suitable for the Android ecosystem. The Kotlin library is very small, so we will not introduce additional costs in the development process. The size is equivalent to the support-v4 library, and the libraries we use in many projects are larger than Kotlin. In addition, Android Studio (the official Android IDE) is built based on IntelliJ idea. This means that our IDE provides great support for this language. We can quickly configure the project and use the familiar IDE for development. We can continue to use the various running and debugging features provided by Gradle and IDE. This is similar to developing applications using Java. Thanks to the interoperability, we can use the Android sdk in the Kotlin code without any problems. In fact, some sdks become easier to use, because interoperability is very intelligent. For example, it can map getters and setters to the Kotlin attribute, we can also write listeners in the form of closures.

How to Use Kotlin in Android development?

The process is very simple, just follow the steps below:

Download the Kotlin plug-in from IDE plugins and create the Kotlin class in the module using "Configure Kotlin in Project ..." Start Encoding

Features of Kotlin

Kotlin has a lot of impressive features, which cannot be described here. But let's take a look at some of the most important features.

Null Security

As mentioned above, Kotlin is null safe. If a type may be null, we need to add a? After the type ?. In this way, every time we use this type of variable, we need to perform the null check. For example, the following code cannot be compiled:

Var artist: Artist? = Null? Artist. print ()

The 2nd row displays an error because no null check is performed on the variable. We can do this:

If (artist! = Null ){? Artist. print ()?}

This shows another outstanding feature of Kotlin: intelligent type conversion. If you check the type of the variable, you do not need to perform type conversion on it in the check scope. In this way, we can now use artist as a variable of the Artist type in if. This is also applicable to other checks. There is also a simpler way to check null, that is, before calling the function of the object ?. You can even use the Elvis operator? Another approach is provided:

Val name = artist ?. Name? :""

Data

In Java, if you want to create a data class or POJO class (only classes with some States saved), you need to create a class with a large number of fields, getters and setters, the toString and equals methods may also be provided:

Public class Artist {private long id; private String name; private String url; private String mbid; public long getId () {return id;} public void setId (long id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getUrl () {return url;} public void setUrl (String url) {this. url = url;} public String getMbid () {return mbid;} public void setMbid (String mbid) {this. mbid = mbid ;}@ Override public String toString () {return "Artist {" + "id =" + id + ", name = '"+ name +' \'' + ", url = '" + url +' \ ''+ ", mbid = '"+ mbid +' \'' + '}';}}

In Kotlin, the above Code can be written as follows:

Data class Artist (? Var id: Long, var name: String, var url: String, var mbid: String)

Kotlin uses attributes instead of fields. Basically, the attribute is the field plus its getter and setter.

Interoperability

Kotlin provides some excellent interoperability features, which is very helpful for Android development. One of them is the ing between interfaces with a single method and lambda expressions. In this case, click the listener:

View. setOnClickListener (object: View. OnClickListener {override fun onClick (v: View) {toast ("Click ")? }?})

It can be written as follows:

View. setOnClickListener {toast ("Click ")}

In addition, both getters and setters are automatically mapped to attributes. This will not cause performance loss, because the bytecode actually only calls the original getters and setters. The following code is used:

SupportActionBar. title = titletextView. text = titlecontactsList. adapter = ContactsAdapter ()

Lambda expressions

Lambda expressions can streamline code to a great extent, but it is important that with Lambda expressions, we can do things that cannot be implemented or implemented before. With Lambda expressions, we can think about problems in a more functional way. Lambda expressions are actually a specific type and define a function. For example, we can define a variable as follows:

Val listener: (View)-> Boolean

This variable can declare a function that receives a view and returns this function. We need to define the function behavior through the closure method:

Val listener = {view: View-> view is TextView}

The above function will receive a View. If the view is a TextView instance, it will return true. Since the compiler can deduce the type, we do not need to specify it. It can also be clearer:

Val listener: (View)-> Boolean = {view-> view is TextView}

With Lambda expressions, We can discard the use of callback interfaces. You only need to set the function to be called later:

Fun asyncOperation (value: Int, callback: (Boolean)-> Unit) {... callback (true )?} AsyncOperation (5) {result-> println ("result: $ result ")}

There is also a more concise method. If the function only receives one parameter, you can use the reserved word it:

AsyncOperation (5) {println ("result: $ it ")}

Anko

Anko is a library developed by the Kotlin team to simplify Android development. Its main goal is to provide a DSL that uses the Kotlin code to declare the View:

VerticalLayout {val name = editText () button ("Say Hello") {onClick {toast ("Hello, $ {name. text }! ")}}}

It also provides some other useful features. For example, navigate to another Activity:

StartActivity ("Id" to res. id, "name" to res. name)

Summary

As you can see, Kotlin simplifies Android development in many aspects. It will increase your productivity and solve some common problems in a very different and simpler way.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.