Site Loader
Join Academy

Hi guys, this article will be interesting especially for the Android Lovers and Enthusiasts. Now, a lot has changed in Android Development. First, Google has announced a new programming Language for Android, know as Kotlin. Kotlin is a statically-typed programming language that runs on the JVM. It can also be compiled to JavaScript source code.

Ever since Apple released the Swift programming language for iOS, lots of Android developers have wanted a similar language for Android development. If you are one of those developers, you are going to love Kotlin, a JVM language that is remarkably similar to Swift.

Android Development Introduction Using Kotlin covers all the needed basics to start developing using Kotlin in your first simple app. Kotlin has some amazingly cool features! This is what we will be learning and using in this blog.

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.

When creating native apps for Android, you will normally use the Java programming language for your logic. Whilst Java is a battle hardened language, it isn’t without its issues.
JetBrains, known for IntelliJ IDEA (Android Studio is based on IntelliJ), has introduced the Kotlin language.

Android Development Introduction Using Kotlin

Since Android took the world by storm, developers have had no alternatives to Java app development. Although its usage is widespread, Java comes with a lot of historical baggage.

Java 8 solved some language issues and corrected even more with Java 10. In order to get much of a benefit from the corrections made in these two releases, you have to set the minimum SDK to Android 24 just to use Java 8, which isn’t an option for many developers. For almost everybody, Java 10 isn’t even on the radar.

Kotlin aims to fill that gap of a missing modern language for the Android platform. There are a few core tenets that Kotlin lives by; it strives to be:

  1. Concise to reduce the amount of boilerplate code you need to write.
  2. Expressive to make your code more readable and understandable.
  3. Safe to avoid entire classes of errors such as null pointer exceptions.
  4. Versatile for building server-side applications, Android apps or frontend code running in the browser.
  5. Interoperable to leverage existing frameworks and libraries of the JVM with 100 percent Java interoperability.

Above all, it’s a new language! What could be more exciting? iOS developers can’t have all the fun. :]

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.

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

2. Creating the Project

Click File -> New Project

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

Finally, Click Finish.

3. Java to Kotlin Conversion

By default, Android Studio creates the following Activity Template

package com.androidstudy.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.androidstudy.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

Then select Configure Kotlin in Project

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.androidstudy.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.androidstudy.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.androidstudy.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 - Android Study!"
    }
}

Run The Project

Hope this tutorial gave a glimpse of how useful Kotlin is for Android Development. You should consider it for your next project! Remember to leave a comment or a question below and I will get back as soon as possible.

You can learn more about Android architecture best practices here.

Have a nice one guys!

You can clone or download the project from Github here! 

Happy Coding!

Post Author: academy

School of {Code}

2 Replies to “Android Development Introduction Using Kotlin”

Leave a Reply

Your email address will not be published. Required fields are marked *

Academy Archives

Categories