1. 程式人生 > >Kotlin for Android (I): Introduction

Kotlin for Android (I): Introduction

Kotlin is one of the many JVM based languages that are starting to emerge as a possible Java successor in Android development. Java is one of the most used languages in the world, and while many other languages evolve to make programmers lives easier, Java has not been able to keep their track as fast as expected.

It seems that many of the things Java lacks are being covered in latest revision, but Android developers won´t be able to take advantage of them for many years. That´s the interest behind the use of Kotlin and similar languages: being able to use modern programming techniques in our ancient environment.

What´s Kotlin?

Kotlin is a JVM based language created by JetBrains, the team behind IntelliJ, which is the base for Android Studio. It´s an object oriented language that includes many ideas from functional programming.

Kotlin was born with the idea of covering those gaps Java leaves and add much more simplicity to the code saving us from writing as much boilerplate code as possible.

Why Kotlin?

My first disclaimer is that I haven´t tried any other alternatives to Kotlin such as Go or Scala, so I recommend searching what other people thinks about those languages if you are really thinking on switching to another language. An awesome example of Android using Scala can be found in 47deg Github site.

These are the reasons why I chose Kotlin as a study case:

  • Relatively fast learning curve: compared to Scala for instance, we are moving in a much simpler scope. Kotlin is much more limited, but it´s easier to start if you´ve never used a modern language before.
  • Lightweight: Kotlin library is small compared to others. This is important because Android method limit is always a problem, and though there are some options to solve it such as proguard or multidexing, all of these solutions will add complexity and will be time consuming when debugging. Kotlin adds less than 7000 methods, more or less the same as support-v4.
  • Highly interoperable: It works extremely well with any other Java libraries, and the interoperability is very simple. That´s one of the main ideas the Kotlin team kept in mind while developing this new language. They want to use it to continue developing their current projects written in Java without having to rewrite the whole code. So Kotlin needs to be extremely interoperable with Java code.
  • Perfectly integrated with Android Studio and Gradle: we have one plugin for the IDE and another one for Gradle, so it won´t be difficult to start an Android project using Kotlin (this is what I´ll talk about in the next article).

An interesting document I recommend reading before taking any decision is the one Jake Wharton wrote about the use of Kotlin for Android development.

What do we get with Kotlin?

1. Expressiveness

With Kotlin, it´s much easier to avoid boilerplate because most typical situations are covered by default in the language.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

For instance, in Java, if we want to create a typical data class, we´ll need to write (or at least generate) this code:

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

How much code is this on Kotlin? Just this simple data class:

data class Artist(
    var id: Long, 
    var name: String, 
    var url: String, 
    var mbid: String)

2. Null safety

When we develop using Java, most of our code is defensive. We need to check continuously if something is null before using it if we don´t want to find unexpected NullPointerException. Kotlin, as many other languages, is null safe because we need to explicitly specify if an object can be null by using the safe call operator.

We can do things like 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 functions

We can add new functions to any class. It´s a much more readable substitute to the typical utility classes we all have in our projects. We could, for instance, add a new method to fragments to show a toast:

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

We could now do:

fragment.toast("Hello world!")

4. Functional support (Lambdas)

What if instead of having to write the creation of a new listener every time we need to declare what a click should do, we could just define what we want to do? We can indeed. This (and many more interesting things) is what we get thanks to lambda usage:

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

Conclusion

Kotlin is a very interesting alternative to Java for developing Android apps. Next articles will describe how to start a new project using Kotlin, and how to take the most out of the language to make Android development easier. Stay tuned!

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Kotlin for Android (I): Introduction

Kotlin is one of the many JVM based languages that are starting to emerge as a possible Java successor in Android development. Java is one of the mos

Kotlin recipes for Android (I): OnGlobalLayoutListener

Today a mate asked me how he could do an OnGlobalLayoutListener properly without incurring in the need of too much boilerplate. This was a tricky que

快速切換至Kotlin for Android模式

前言 關於Kotlin的文章,已經構思了很久。一直不知道該怎麼寫。文件式文章?那不如直接看文件,何必需要我再多“嗶嗶”呢。思來想後,決定寫一篇快速在Android開發中感受Kotlin的其妙的文章。 說實話,最開始搞Kotlin我是拒絕的。為啥?因為完全沒有感覺到用它替換Java開發有什麼實質性的改變;而

極簡Kotlin-For-Android(一)

安裝 Kotlin 外掛 Android Studio 3.+ 已經有了 Kotlin 外掛,如果是更早的版本,點選 Android Studio | File | Settings | Plugins,搜尋 Kotlin ,安裝,重啟 Android Studio . 建立工程 點選 Android

極簡Kotlin-For-Android(二)

上一篇我們做到了從網路獲取資料,並寫好了實體類.接著我們需要建立domain層,這一層為app執行任務. 構建domain層 首先需要建立command: public interface Command<T> { fun execute() : T } 複製程式碼 建立DataMap

Blog-08-《一週快速上手Kotlin For Android》-之ArrayList

在 Kotlin 中沒有實現和 Java 一樣的 List 集合,而是使用了和 Java 一樣的 ArrayList 集合。Kotlin 中提供了以下四種函式方法來使用 ArrayList,分別是 1、listOf()2、listOfNotNull()3、mutableListOf()4、arraylistO

Blog-06-《一週快速上手Kotlin For Android》-之When分支

—《一週快速上手Kotlin For Android》簡介目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Jav

Blog-04-《一週快速上手Kotlin For Android》-之Activity詳細用法

—《一週快速上手Kotlin For Android》簡介 目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Java對於你來說才是真正的開發”利器”,使用Java你能發揮

Kotlin for Android

在Google IO 2017 大會上,Google將 Kotlin列為 Android官方開發語言,Android Studio 3.0 也預設集成了Kotlin外掛。 如果您是更早的版本,點選Android Studio File->Settin

Blog-07-《一週快速上手Kotlin For Android》-之陣列

—《一週快速上手Kotlin For Android》簡介目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Java對於你來說才是真正的開發”利器”,使用Java你能發揮更高的效率,當然,如果如此你還是可以繼續使用Java

Kotlin for Android(九)Kotlin集合

一、結構 集合在我們實際開發中用的還是比較頻繁的,Kotlin中的集合不同於Java中的集合, Kotlin中的集合根據“是否可變”,分為兩派:可變集合與不可變集合(可變集合可以在初始化後add新資料,不可變集合只能get資料,不能add資料),而後者是 在前

一步步學習kotlin for android(三) kotlin省略findviewById

findViewById      今天的內容涉及到findViewByID,android語言原來這個特別繁瑣,現在好了,kotlin語言,直接拿來佈局裡面的id用,省去好多重複工作量啊 在使用kotlin的id之前,需要先在builde.gradle裡引入這個 app

Kotlin for Android Developers

If at any time you have tried to investigate on your own, then you are aware of the amount of time we sometimes spend to find the solution we are loo

Kotlin for Android (III): Extension functions and default values

Now that you know the basics about Kotlin and how to configure your project, it´s time to talk about some interesting things that Kotlin can do for u

Kotlin for Android (II): Create a new project

After getting a light idea of, it´s time to configure Android Studio to help us develop Android apps using Kotlin. It requires some steps that only n

Kotlin for Android Developers: The book

Hi dear reader. Today it’s a very special post, because I’m really happy to announce the release of my first book: Kotlin for Android Developers is

Kotlin for Android (IV): Custom Views and Android Extensions

After reading what can do for you, you might be wondering what´s next. As we talked in , this language makes Android development much simpler and th

12 reasons why you should start using Kotlin for Android today

Even now that Kotlin is an officially supported language to write Android Apps, you may still feel that there are not enough reasons for a change. Ja

Who is Open Source? Android O Preview 3. Kotlin for Android. And Vaadin 8!

GitHub Survey: Open Source is Raining Men! A 2017 GitHub survey of 5500 randomly selected participants, most of whom work on GitHub.com open source pro

Learn Kotlin while developing an Android App (Introduction)

ContentIntroductionWelcome to this series of Stories where we are going to learn Kotlin, a new JVM language, while developing an Android App. I hope it wil