Developing Android Applications with Kotlin (I): Introduction

Source: Internet
Author: User

About Kotlin, there have been some articles on the web, including Antonio Leiva's blog translation. However, I would like to follow them, translate them, to exercise their English translation. Experts find the problem, please timely "shoot bricks."

Original title: Kotlin for Android (I): Introduction (http://antonioleiva.com/kotlin-for-android-introduction/)

Original Antonio Leiva (http://antonioleiva.com/about/)

Published in the original: 2015-03-09

Kotlin is one of the many JVM-based programming languages . In Android development, it may become a Java successor. Java is one of the most commonly used languages in the world, and while many other programming languages are evolving to make it easier for programmers to use, Java has not been able to keep up to date as expected.

Many of the shortcomings of Java have been fixed in the latest revisions, but Android developers are not using them for the time being. This is the attraction of using Kotlin and similar languages: using advanced programming techniques in the current development environment.

What is Kotlin?

Kotlin is a JVM-based programming language created by JetBrains (https://www.jetbrains.com/), and IntelliJ is also a JetBrains team, while Android Studio is also based on IntelliJ. It is an object-oriented programming language that includes many functional programming ideas.

Kotlin was born to make up for the flaws in Java. It greatly simplifies the code, allowing us to save writing a lot of boilerplate code work.

Why use Kotlin?

First of all, I affirm that I have not been using Kotlin for a long time, and I am almost learning and writing these articles. I have not tried other languages such as go or Scala, so if you really want to change other languages, I suggest you first search how other people rated you to convert the programming language. A good example of using the Scala language to develop Android apps can be found in the GitHub 47deg Project (Http://47deg.github.io/translate-bubble-android/).

These are the reasons why I chose Kotlin to study:

    • learning curve relatively quickly (path): We are in a much simpler area than Scala instances. Kotlin has a lot of limitations, but even if you've never used a modern language before, it's easy to get started.
    • Lightweight : The Kotlin code base is smaller than other languages. This is important. Because the limitations of the Android method are always a problem, although there are other solutions (such as Proguard or multidexing), all of these solutions are complex and time-consuming to debug. Kotlin increased by less than 7,000, similar to support-v4.
    • High Interoperability : It works well with other Java code libraries and is very easy to interoperate with. This is one of the key ideas that Kotlin team has to keep in mind when developing a new language. They want to use it to continue developing projects that are currently being developed in Java, without having to rewrite the entire code. So Kotlin needs to be very interoperable with Java code.
    • perfectly integrated with Android studio and Gradle : We have IDE plugins and Gradle plugins, so there's no difficulty in developing Android projects with Kotlin (which I'll discuss in the next article).
    • Before making a decision, I suggest reading Jake Wharton's Android Development using Kotlin (https://docs.google.com/document/d/ 1res3ep-hjxwa8kzi0yqdbehcqtt29hg8p44aa9w0dm8/edit?hl=es&forcehl=1) article. This is an article of concern.

What do we get from the Kotlin?

1. Expression

With Kotlin, you can easily avoid writing boilerplate code because the default values for programming languages already cover most typical situations.

For example, in Java, if you want to create a typical data class, you need to write (or at least produce) the code:

1  Public classArtist {2     Private LongID;3     PrivateString name;4     PrivateString URL;5     PrivateString mbid;6  7      Public LonggetId () {8         returnID;9     }Ten   One      Public voidSetId (LongID) { A          This. ID =ID; -     } -   the      PublicString GetName () { -         returnname; -     } -   +      Public voidsetName (String name) { -          This. Name =name; +     } A   at      PublicString GetUrl () { -         returnURL; -     } -   -      Public voidseturl (String url) { -          This. url =URL; in     } -   to      PublicString getmbid () { +         returnMbid; -     } the   *      Public voidsetmbid (String mbid) { $          This. Mbid =Mbid;Panax Notoginseng     } -   the@Override PublicString toString () { +         return"Artist{" + A"id=" + ID + the", Name= ' + name + ' + ' + +", url= ' + URL + ' \ ' + -", mbid= '" + mbid + "+ $‘}‘; $     } -}

How much code do you need with Kotlin? The data classes are as simple as this:

1 class Artist (2    3 45             var mbid:string)

2. Empty type safety

Most of the code is preventative when it comes to Java development. In order to not encounter unexpected nullpointerexception, it is necessary to constantly detect whether the object is empty before use. As with many other languages, Kotlin is empty type safe because it is necessary to explicitly indicate whether an object can be empty (null)using the Secure call operator (http://kotlinlang.org/docs/reference/ null-safety.html).

You can do this:

1 //This won´t compile. Artist can´t be null2var notnullartist:artist =NULL3 4 //Artist can be null5var artist:artist? =NULL6 7 //won´t compile, artist could is null and we need to deal with that8 Artist.print ()9 Ten //Would print only if artist! = NULL OneArtist?. Print () A  - //Smart cast. We don´t need to use safe call operator if we previously checked nullity - if(Artist! =NULL) { the Artist.print () - } -  - //Only with the it when we is sure it´s not null. Would throw an exception otherwise. +artist!!. Print () -  + //Use Elvis operator to give a alternative in case the object is null AVal name = artist?. Name?: "Empty"

3. Extension function

You can add new functions for any class. In a project, replacing an existing typical utility class can make your code more readable. For example, add a new function for fragment to display toast:

1 Fun fragment.toast (message:charsequence, duration:int = toast.length_short) {2     Toast.maketext (getactivity (), message, duration). Show ()3 }

You can now do this:

1 fragment.toast ("Hello world!")

4. Functional Support (Lambdas)

If you don't want to create a new listener every time you declare a click action, can you directly define what you want to do? The answer is yes. This (including many more interesting features) is attributed to the use of lambda expressions:

1 view.setonclicklistener ({toast ("Hello world!")})

Current limitations

Although Kotlin is very stable and will release the final version soon (this summer), it is still under development and has some limitations for Android app development:

    • Interoperability with autogenerated code : Some well-known Android libraries, such as dagger or butterknife, are dependent on autogenerated code and cannot work due to some naming incompatibility. The Kotlin team is dealing with this issue and will be resolved one day (kt-6444:https://youtrack.jetbrains.com/issue/kt-6444). In any case, as I explained in the next article, the ability to express language makes us think that we don't need those libraries.

Update: Kotlin M12 is now introduced to support annotation processing.

    • customizing the View declaration method is not simple enough : the Kotlin class can only declare one constructor, and a custom view typically requires three. If you use class programming, this is not a problem, but XML usage is not enough. The easiest workaround is to declare these classes in Java and then use them in Kotlin. The Kotlin team is committed to resolving (https://youtrack.jetbrains.com/issue/KT-2095) in the M11 release.

Update: Kotlin M11 was released and includes an auxiliary constructor (http://kotlinlang.org/docs/reference/classes.html#constructors).

    • Android JUnit test for the project : The new features of Android Studio 1.1 may also be used in Kotlin. By the way, in pure Kotlin projects, instrumentation testing and junit testing are fully functional.

Update: The Kotlin M12 gradle plugin is now available for unit testing .

Summarize

For the development of Android App,kotlin is an interesting Java replacement. The next article will show you how to create a new project with Kotlin and how to use language features to make Android development easier. Please pay attention!

Developing Android Applications with Kotlin (I): Introduction

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.