Kotlin-for-android introduction (making your Android code more concise), kotlinandroid

Source: Internet
Author: User

Kotlin-for-android introduction (making your Android code more concise), kotlinandroid

  • Original article: Kotlin for Android (I): Introduction
  • Translator: canglangwenyue
  • Proofreader: Mr. Simple
  • Status: complete

Kotlin is one of the many JVM-based languages. It was initially used as a possible substitute for the java language in android development. Java is one of the most widely used languages in the world, and the development of other languages makes programming easier for programmers, but java has not developed as soon as possible.

Kotlin Introduction

Kotlin is a JVM-based language created by JetBrains, and JetBrains is the creation team of IntelliJ idea.
Kotlin is an object-oriented programming language with many functional programming features.

Why use Kotlin?

I first declared that I didn't use Kotlin for a long time. I wrote these articles almost simultaneously. I didn't try any other alternative languages, such as Go and Scala, so if you really want to change the development language, I suggest you search for other people's comments on these languages. An example of android development using Scala can be found at [47deg Github site] (http :/
47deg. github. io/translate-bubble-android.

The following are the reasons why I chose to learn Kotlin:

  • Relatively Fast Learning Curve: Using Scala as an example for comparison, we are moving towards a simpler direction. Kotlin has more restrictions, but if you have never studied a modern programming language, Kotlin is easier to learn.
  • Lightweight: Compared with other languages, Kotlin has a smaller core library. This is important because the number of android functions is limited (the number of functions cannot exceed 64 k ).
    However, there are some options to solve this problem, such as proguard or multidexing, but these solutions will increase the complexity and
    It takes more time for debugging. Introducing the Kotlin core library adds less than 7000 methods, roughly the same as support-v4.
  • High Interaction: Kotlin is well-coordinated with other java libraries, and interactive operations are simple. This is the Kotlin team.
    Developing a new language is one of the main concepts. They want to use Kotlin for development without rewriting all the Code previously written in java. Therefore, Kotlin and java must be highly interactive.
  • Perfect Combination with AS and Gradle: We have an IDE plug-in and another Grade plug-in. Therefore, we use Kotlin
    Android programming is not difficult.

Before starting any argument, I suggest you take a look at the interesting document the use of Kotlin for Android development written by Jack Wharton.

Advantages of Kotlin 1. Higher readability and simplicity

With Kotlin, it is easier to avoid creating template-type code, because most classic scenarios are included in Kotlin by default.
For example, in java, we need to do this when we want to create a typical data class:

    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 + '\'' +                '}';    }}

So how much code does Kotlin need? This is just the following simple data class:

    data class Artist(    var id: Long,     var name: String,     var url: String,     var mbid: String)
2. NULL pointer Security

When we use java for development, most of our code requires type check. If we do not want to see ** unexpected
NullPointerException **, We need to continuously check whether any object is null before running the code. Kotlin, and other languages
Similarly, it is null pointer safe, because we can accurately declare an object to be null through secure call operations.

We can do this:

    //This won´t compile. Artist can´t be null    var notNullArtist: Artist = null    //Artist can be null    var artist: Artist? = null    // Won´t compile, artist could be null and we need to deal with that    artist.print()    // Will print only if artist != null    artist?.print()    // Smart cast. We don´t need to use safe call operator if we previously checked     nullity    if (artist != null) {        artist.print()    }    // Only use it when we are sure it´s not null. Will throw an exception otherwise.    artist!!.print()    // Use Elvis operator to give an alternative in case the object is null    val name = artist?.name ?: "empty"
3. Extension Method

We can add new methods to any class. This is more readable than the tool class we use in the project. For example, we can add a new method for Fragment to display Toast.

fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {    Toast.makeText(getActivity(), message, duration).show()}

We can use this method as follows:

    fragment.toast("Hello world!")
4. Support for functional programming

If we do not need to create a listener every time we need it, it is like creating a click listener operation,
Instead, it just defines what we want to do? This idea can indeed be implemented, and its implementation benefits from the use of ** lambda ** d:

    view.setOnClickListener({ toast("Hello world!") })
Kotlin restrictions

Kotlin is still developing. Although it is relatively stable and the final release version is soon released, Kotlin still has some restrictions during android-related development.

  • Interaction and Automatic Code Generation: Some famous android Libraries, such as Dagger or Butterknife, depend on automatic
    Code generation. In this case, if there is a name conflict, the Code cannot be generated. Kotlin is solving this problem, so this problem may
    It will be solved soon. In any case, I will explain in the following article that the expression ability of the Kotlin language will make us feel that we no longer need so many
    Libraries.

  • It is difficult to declare a custom View.: The Kotlin class can only declare one constructor. However, a custom View usually requires three constructors. If I
    You can avoid this problem by using code to create a View. However, if you declare a View using an XML file, the requirements cannot be met. The easiest work und is to use java to declare these
    Customize the implementation classes of the View and use them through Kotlin. The Kotlin team promised to solve the problem in the M11 release.
    Update: Kotlin M11 is out and now has des secondary constructors

  • Junit test in android: The new features described in AS 1.1 are not applicable to Kotlin. By the way, system testing and Junit testing are completely available for pure Kotlin projects.

Conclusion

For android apps development, Kotlin is an interesting replacement for java. The next article will describe how to use Kotlin to create
Projects, and how to better apply Kotlin to make android development easier. Stay tuned!

This article is from https://github.com/bboyfeiyu/android-tech-frontier. welcome to star and fork.
The front line of Android development technology. Please pay attention to the subscription number when translating high-quality Android technical articles abroad.

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.