Pages

Tuesday, June 6, 2017

Setup Kotlin Plugin for Android Studio 2.3

AndroidDev annouce officially adding support for the Kotlin programing language. Check here Android Developer Blog.

The Kotlin plug-in is now bundled with Android Studio 3.0. Kotlin was developed by JetBrains, the same people who created IntelliJ. Also Kotlin pluging available for Android Studio 2.3.2 version. See below how to add plugin Kotlin in Android Studio lower vsersion.

Let's Start to setup

Install Kotlin Plugin for Android Studio


In Windows PC : Open File>Setting>Plugins>Browse Repositories (Preferences > Plugins > Browse Repositories). Search Kotlin and Install.

 
When the install is complete, you will need to restart Android Studio to apply the new plugin.

Apply Kotlin Plugin to the project


First of all create a new Android Project. File>New>New Project and follow through project creation steps.

Next step to apply the Kotlin Plugin to both build.gradle files at the Project level and app-module level. There is an automated tools to do this, but sometimes the manual process of applying the plugin in our build.gradle files.

First we need to add the plugin to the root project build.gradle.

 
buildscript {
    ext.kotlin_version = "1.1.2-4" // replace with the latest (stable) version: https://github.com/JetBrains/kotlin/releases/latest

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

Second we need to add the plugin to the app-module build.gradle. To add apply plugin : kotlin-android in build.gradle file

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

Convert Java Code to Kotlin


We setup all we need, but our Empty Activity still in java. Here show how to convert java file to Kotline. Way to convert java file to Koitlin Select Code>Convert Java File to Kotlin or use shortcut - control + Alt + Shift + K  (Replace control to Command if you are using MAC)

MainActivity.java
package com.limbani.helloworld;

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);
    }
}

After converting code to Kotlin. MainActivity.kt look like below
package com.limbani.helloworld

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

class MainActivity : AppCompatActivity() {

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

Thanks for reading this post. I will be writing tutorial for Kotlin language.

Resource
https://kotlinlang.org
Android Developer Blog
 

No comments:

Post a Comment