Codementor Events

Getting Started with Kotlin For Android Development

Published Jan 03, 2017Last updated Jan 18, 2017
Getting Started with Kotlin For Android Development

Introduction to Kotlin

As defined by Ashraff Hathibelagal in this tutorial:

Kotlin is a statically-typed language, developed by JetBrains, with syntax more expressive and concise than that of Java. With features like higher-order functions, lambda expressions, operator overloading, string templates, and more, Kotlin has a lot more to offer than Java. Because Java and Kotlin are highly interoperable, they can be used together in the same project.

Using Kotlin in Android

Using Kotlin into your Android application is quite easy — just follow these steps!

1. Installing Kotlin Plugin for Android Studio

In your Android Studio go to File -> Settings -> Plugins and click Browse Repositories and then search for Kotlin.

kotlin for android

Click the "Install" button. Once the Kotlin plugin is installed, restart Android Studio

2. Creating the Project

Click File -> New Project

kotlin for android

Enter the detail about the project, then select Phone and Tablet and click "Next", select empty layout and click "Next"

kotlin for android

Finally, Click Finish.

3. Java to Kotlin Conversion

By default, Android Studio creates the following Activity Template:

package com.poovarasan.kotlindemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

In order to convert this Java Template to Kotlin, Press CTRL + ALT + SHIFT + K (or) click Code -> Convert Java File to Kotlin. Doing this will convert Java files to Kotlin and the code becomes:

package com.poovarasan.kotlindemo

import android.os.Bundle
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

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

4. Configure Kotlin for your Android Project

Press shift twice in Android Studio Editor. You should be able to see finder, then you should type convert Kotlin

kotlin for android

Then select Configure Kotlin in Project

kotlin for android

Click the OK Button and Sync the project. Your main build.gradle becomes:

buildscript {
    ext.kotlin_version = '1.0.5-2'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And your project build.gradle becomes:

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

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.poovarasan.kotlindemo"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
repositories {
    mavenCentral()
}

Using the Kotlin Android Extension

The Android Kotlin extension gives an easy way to inject layout into your Kotlin activity:

apply plugin: 'kotlin-android-extensions'

Add the line above in your app's build.gradle file and sync your project. And in the activity_main.xml...

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.poovarasan.kotlindemo.MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/helloText"/>
</RelativeLayout>

I created a TextView with id _helloText_. In the activity class, you can inject the TextView using their ID.

package com.poovarasan.kotlindemo

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        helloText.text = "Kotlin Example"
    }
}

Run The Project

kotlin for android

Wrapping up

Hope this tutorial gave a glimpse of how useful Kotlin is for Android Development. You should consider it for your next project!

Discover and read more posts from Poovarasan
get started
post comments3Replies
Marvin sosa soto
6 years ago

could you give more explanation about this:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

Versatile Mobitech
6 years ago

Great Share!

Versatile Mobitech is a Software Development Company based out of Hyderabad, We have pool of talented IT professionals who are technically sound in latest software development technologies like UX/UI Design, Website / Web Application Development, Mobile Applications Development, Digital Marketing and SEO, IT Consulting and Tech Support.

For more info visit: versatilemobitech.com

kuldeep patel
7 years ago

hello, i want to learn android programming.please help me