What Android developers should know about Kotlin

Source: Internet
Author: User

This article is from my translation of the Infoq Chinese station, the original address is: http://www.infoq.com/cn/news/2016/01/kotlin-android


Android developers face a dilemma with language restrictions.

As we all know, the current Android development only supports Java 6 (the language itself has been improved from Java 7), so we can only use an ancient language for development every day, which greatly reduces our productivity, At the same time, forcing us to write a lot of boilerplate and fragile code. However, this code is difficult to read and maintain.

Fortunately, the Android program is executed on top of the Java virtual machine, so technically everything that can be done on the JVM can be used to develop Android apps. There are many languages that can generate bytecode that can be executed by the JVM, some of which have started to emerge and become popular, and Kotlin is the leader.

What is Kotlin?

Kotlin is a language that executes on top of the JVM. It is created by JetBrains. And JetBrains is the company behind many powerful tools, such as the well-known Java IDE IntelliJ idea.

Kotlin is a very easy language, one of its main goals is to provide powerful language at the same time and maintain simple and concise syntax. The main features are as follows:

    • Lightweight: This is important for Android. The library needed for the project should be as small as possible. Android has a strict limit on the number of methods, and Kotlin only adds about 6,000 additional methods.

    • Interop: Kotlin can communicate seamlessly with the Java language. This means that we are able to use any existing Java library in the Kotlin code, so even though the language is still very young, it has been able to use hundreds or thousands of libraries. In addition, the Kotlin code can be used for Java code, which means that we can use both languages to build software.

      You can use Kotlin to develop new features. Use Java at the same time to implement other parts of the code base.

    • Strongly typed: We seldom need to specify a type in the code, since the compiler can determine the type of the variable or function return value in most cases. This gives you two advantages: simplicity and safety.
    • Null security: One of the biggest problems with Java is null. Assuming that there are no null judgements for variables or arguments, it is possible to throw a lot of nullpointerexception in the program, but these are difficult to detect when coding. Kotlin uses explicit null, which forces us to check for null if necessary.

Now the Kotlin version number is 1.0.0 Beta 3. Only the official version will be announced soon. It can be used entirely in production. Today, many companies have successfully applied Kotlin.

Why is it that Kotlin is suitable for Android?

Basically. This is because all of Kotlin's features are well suited to the Android ecosystem.

The Kotlin library is small and we do not introduce additional costs in the development process.

Its size is equivalent to the SUPPORT-V4 library. The libraries we use in many projects are larger than Kotlin.

Besides. Android Studio (the official Android IDE) is built on IntelliJ. This means that our IDE provides great support for the language. We can quickly configure the project and use the familiar IDE for development.

We are able to continue to use gradle and the various execution and debugging features provided by the IDE. This is indistinguishable with developing applications using Java. Thanks to interoperability, we are able to use the Android SDK in Kotlin code without encountering any problems. In fact, some SDKs are easier to use because interoperability is smart, for example, to map getters and setters to Kotlin properties. We can also write listeners in the form of closures.

How do I use Kotlin in Android development?

The process is easy, just follow the steps below to get it right:

    • Download the Kotlin plugin from IDE plugins
    • Creating the Kotlin class in the module
    • Use "Configure Kotlin in Project ..."
    • Start coding

Some features of Kotlin

Kotlin has a lot of very impressive features, here can not be introduced, but we look at the most important.

NULL security

As mentioned earlier, Kotlin is null-safe.

Assuming that a type might be null, then we need to add one after the type?

。 This way, each time a variable of that type is used. We all need a null check.

Let's say, for example, the following code will fail to compile:

var artist:artist? = Null?artist.print ()

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

if (artist! = null) {? Artist.print ()?}

This shows another excellent feature of Kotlin: Intelligent type conversion.

Suppose you check the type of a variable, you do not need to type it in the scope of the check. Such We are now able to use artist as a variable of type artist in the IF.

This is also true for other checks. Another simpler way to check for NULL is to use it before invoking the function of the object.

。 You can even use the Elvis operator to provide a second approach:

Val name = artist?. Name?

: ""

Data classes

In Java, assuming that you want to create a data class or a Pojo class (a class that holds only a few states), we need to create a class with lots of fields, getters and setters, and perhaps a ToString and equals method:

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 () {Retu RN Mbid; The public void Setmbid (String mbid) {this.mbid = Mbid;} @Override the Public String toString () {return "artist{" + "id=" + I D + ", 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 rather than fields.

Essentially, a property is a field plus its getter and setter.

Interop

Kotlin provides some great interoperability features. This is a great help for Android development. One of these is the mapping between an interface with a single method and a lambda expression. So, here's the Click Listener:

View.setonclicklistener (Object:View.OnClickListener {override fun OnClick (V:view) {Toast ("click")}?})

Can be written like this:

View.setonclicklistener {Toast ("click")}

In addition Both getters and setters map themselves to the attribute on their own initiative. This does not result in a performance loss, because bytecode is actually simply called the original getters and setters.

For example, the following code sees:

Supportactionbar.title = Titletextview.text = Titlecontactslist.adapter = Contactsadapter ()

Lambda expression

A lambda expression is a great way to streamline your code, but it's important to use a lambda expression. We can do things that are impossible or difficult to achieve before. With lambda expressions, we can think of problems in a more functional way. A lambda expression is actually a specified type, and the type defines how a function is. Say. We can define a variable like this:

Val Listener: (View), Boolean

The variable can declare a function. It receives a view and returns the function.

We need to define the behavior of the function by means of closures:

Val listener = {View:view, view is TextView}

The above function will receive a view, assuming that the view is an instance of TextView, then it will return true. Because the compiler is able to determine the type. So we don't have to specify. can also be more understanding of some:

Val Listener: (view), Boolean = {view, view is TextView}

With lambda expressions, we can discard the use of callback interfaces. Just set the function that you want to be called later:

Fun AsyncOperation (Value:int, Callback: (Boolean), Unit) {... callback (true)?

} asyncoperation (5) {result-println ("Result: $result")}

In another, more concise way, assume that the function only receives a single parameter. Then you can use reserved word it:

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

Anko

Anko is a library developed by the Kotlin team, designed to simplify Android development. The 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 other activity:

StartActivity

What Android developers should know about Kotlin

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.