1. 程式人生 > >Kotlin for Android (II): Create a new project

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 need to be done first time, but some other Gradle configurations will need to be done on every new project.

For this set of articles, I´ll be creating a reduced version of , an app I created some time ago, which will basically connect to a music rest API and return some info about a set of bands. Go to and take a look at the code.

Create a new project and download Kotlin plugin

Just create a basic Android project with an activity using Android Studio, the same way you would do for a regular project.

Once done, first thing you´ll need is to download Kotling plugin. Go to Android Studio preferences and search plugins. Once there, use search again to find Kotlin plugin. Install and restart the IDE.

kotlin-plugin

Add Kotlin plugin dependency to your application build.gradle

The root build.gradle needs a new dependency that will be required to use the Kotlin plugin in our main module:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:1.5.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.1"
    }
}

Configure module build.grade

First, apply Kotlin plugin:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

Then, add the Kotlin library to your dependencies:

Want to learn Kotlin?

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

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'org.jetbrains.kotlin:kotlin-stdlib:1.0.1'
}

That should be all. However, if your project is mixing both Java and Kotlin files, I recommend you to create a folder for Kotlin sources:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    ...

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

Alternatively, you can skip this step, and after doing next ones, use this Android Studio action:

configure-kotlin-project

I prefer doing it manually to keep my Gradle files organized, but this second option could be easier.

Create Kotlin folder

You can skip this point if you don’t mix Java and Kotlin files. Creating the folder will be easier if you change the project visualization from ‘Android’ to ‘Project’. Go to ‘app->src->main’ and create a folder called ‘kotlin’:

kotlin-folder

Convert java activity to a kotlin file

Kotlin plugin can convert from Java to Kotlin classes. We can convert our current activity to a Kotlin class very easily from ‘Code’ menu, by choosing ‘Convert Java File to Kotlin File’:

convert-java-to-kotlin

IDE will suggest to move new file to the Kotlin folder. Click on ‘Move File’ (or move it manually if you don´t see the option).

You will get a very similar code translated to Kotlin. I suggest taking a look until you understand the differences:

class MainActivity : ActionBarActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item.getItemId()

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true
        }

        return super.onOptionsItemSelected(item)
    }
}

Main differences

Just taking a look at previous code, we can see some direct differences. There are many more we´ll be discovering in next posts:

  • Use of colon instead of the word ‘extends’
  • Explicit use of ‘override’: in Java, we can use an annotation to make our code more clear, but it´s not a condition. Kotlin will force us use it.
  • Use of ‘fun’ for functions: Kotlin is and object-oriented functional language, so it will be very similar to other languages such as Scala. Java methods are represented as functions.
  • Function parameters use a different nomenclature: Type and name are written the other way round and separated by a colon
  • Optional use of semicolons: we don´t need to finish our lines with a semicolon. We can if we want to, but it can save a lot of time and make our code cleaner if we don´t do it.
  • Other small details: In introductory article, I already talked about the ‘?’ symbol on. This indicates the parameter can be null. Nullity is handled different from what we are used in Java

Conclusion

Though we can think using a new language will be very difficult, Kotlin is being created by the JetBrains team to be the most easy and interoperable language to cover the needs Java lacks. As Android Studio is also based on a JetBrains product, it will be very easy to integrate to this IDE and start working with it.

Next article will cover some tips and tricks to make our life easier when developing Android apps with Kotlin.

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 (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 Recipes for Android (II): RecyclerView and DiffUtil

As you may know, the Support Library 24 included a new really handy class called DiffUtil, which will let you get rid of the boring and error prone o

GitHub Desktop 出現“please upgrade your plan to create a new private repository”的解決辦法

ron net please vat tor blog 解決 pos sdn 轉:https://blog.csdn.net/qq_38584262/article/details/82386805 解決辦法:去掉最下面的勾 GitHub

Maven:Failed to create a Maven project ‘…pom.xml’ already exists in VFS 解決

 轉自:https://blog.csdn.net/chenyufeng1991/article/details/73724686 有時候我們在建立Maven專案的時候會出現上述的問題,導致Maven專案建立失敗,報錯的提示如下:       &nbs

快速切換至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

How to create a new business with AI?

Artificial intelligence is about to sweep massively in companies because it is a major element of digital transformation. Automation of low value-added tas

Show HN: PipeGears is a new project that's now in beta and needs your feedback

Hi Everyone,PipeGears http://pipegears.com is new platform for creating and running Web or Mobile Application Backends and API Microservices quickly and ea

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

【轉】How to create a new user and grant permissions in MySQL

MySQL is one of the most popular database management systems. In this tutorial we will cover the steps needed to create new MySQL user and grant permission

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

Maven:Failed to create a Maven project ‘…pom.xml’ already exists in VFS 解決(Mac IntelliJ IDEA)

有時候我們在建立Maven專案的時候會出現上述的問題,導致Maven專案建立失敗,報錯的提示如下:        這往往是由於我們在同一個目錄中建立了Project Name相同的專案導致的。因為在同一目錄下不能建

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