Filed Under: Kotlin

Ever since Google has made Kotlin an official language for Android, the programming language is becoming increasingly popular among developers all around the globe. Some of the questions are:

  • What’s new in Kotlin?
  • Who introduced Kotlin programming language?
  • What’s so special in Kotlin that developers are migrating from Java to Kotlin quickly?
  • Why are Android Developers adopting it so quickly in their projects?

In this tutorial, we’ll be answering all these questions and discuss the nitty gritty details from the beautiful world of Kotlin.

Kotlin

  • Kotlin came up in 2011 from a team of developers at JetBrains.
  • It’s a statically typed language for modern multi-platform applications.
  • Kotlin runs on the Java Virtual Machine and compiles to the JVM Bytecode. It can also be compiled to the Javascript source code. Thus, Kotlin is 100% interoperable with Java. This means that you can call Kotlin code in Java and vice-versa.
  • Interoperability feature is one of the major reasons that’s led to the wide adoption of the kotlin programming language.

Why migrate from Java to Kotlin?

  • Kotlin has a smart concise syntax that helps in reducing the boilerplate code and improving the readability. On contrast, Java is more verbose.
  • Kotlin is type safe compared to Java. It provides a built-in nullability checker for its types (Similar to Optional in Swift).
  • Kotlin has a lean, intuitive and familiar syntax which is easy to master quickly (No semicolons. That’s a blessing!).
  • Kotlin is easy to adopt. All the existing Java frameworks are available for use.

Why are Android Developers migrating to Kotlin?

Besides the above-mentioned pros of Kotlin over Java, two major reasons that are causing the adopting of Kotlin for Android Development are:

  1. Functional Programming

  2. It’s time that the Android Developers start reaping the benefits of Functional Programming.

    Hold on, Java 8 supports Functional Programming through lambda expressions. So why use Kotlin instead?

    As of writing this tutorial, Android fully supports Java 6 only. Java 7 is used since Android API 19. But still more than 50% devices currently are API<19. We’re unsure when would Java 8 support 100% Android devices. This is where Kotlin comes to our rescue. It’s independent of the Android OS. Hence, Kotlin can be updated anytime and the latest features can be used anytime unlike Java.

  3. Reduced Boiler Plate Code

  4. Thanks to the short and concise syntax in Kotlin, it reduces our boilerplate code in Android.

    Sooner you’ll see that the following Java code can be reduced to a much shorter Kotlin code.

    
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //handle click code goes here
        }
    });
    
    
    view.setOnClickListener({//handle click code goes here})
    

Getting Started with Kotlin Programming

There are a few ways to run your Kotlin program:

Download the IntelliJ Community version and get started with your Hello World Kotlin Program below.

kotlin intellij idea home screen

kotlin program type

Select Kotlin/JVM

kotlin project details

kotlin filename

Goto src in the project structure. Right click and select New Kotlin File

Having created the HelloWorld.kt file, let’s write our first program.


fun main(args: Array<String>)
{
    println("Hello World Kotlin")
}

There’s the Kotlin syntax. Don’t worry, we’ll be covering each of the elements of Kotlin at length in the following tutorials. For now, following are important points to remember.

  • fun keyword is used to define a function.
  • The parameter name is followed by a colon and its type.
  • println() function is used to print the input on the console.
  • To run the code, goto the Run dropdown menu. Alternatively, you can click the icon besides the function to run the program too as shown below.
    kotlin hello world program run

    Click on the Kotlin icon

    Once the output gets printed, a folder out gets automatically created in our project structure as shown below.

    kotlin hello world project structure

    HelloWorldKt.class gets created

  • The Kotlin Compiler (kotlinc) converts the .kt file into a .class file. The .class file is then run by the JVM.
  • Notice that the HelloWorldKt.class file gets automatically created by the Kotlin Compiler (You can find the same from Run->Edit Configurations too).

    The above executed kotlin code is equivalent to the Java code below.

    
    public class TestJava{
        public static void main(String[] args)
        {
            System.out.println("Hello World Java");
        }
    }
    
  • A striking difference between the Kotlin main function and the Java one is: You don’t need to explicitly define the main function inside a class in Kotlin. Kotlin covers that stuff for you, unlike Java.

Isn’t the Kotlin code so short and concise!
Note: We haven’t imported the Array clss in the HelloWorld.kt file. That’s because the Kotlin standard library comes up with a bunch of default imports.

The following section demonstrates setting up a Kotlin application in Android Studio.

Android Studio Kotlin

For Android Studio version < 3.0

You’ll need to install the Kotlin plugin. Goto Android Studio Preferences > Plugins > Browse Repositories > search for “Kotlin”.

Once the plugin is installed, goto File > Create a New Module > Choose Java library.

kotlin android studio create new module

Select Java Library

Create a new Kotlin file/class in the newly created Module. Your Project Structure should look like this:

android studio kotlin project structure

Your Android Studio IDE should show a Configure option, since the Kotlin plugin hasn’t been configured in our module yet. Alternatively goto Tools -> Kotlin -> Configure Kotlin in Project would also do.

Your Module build.gradle file would look like this:


apply plugin: 'java'
apply plugin: 'kotlin'

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

sourceCompatibility = "1.7"
targetCompatibility = "1.7"
buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
repositories {
    mavenCentral()
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

Now that Kotlin is configured. You need to Edit the Build configurations as shown below:

kotlin android edit configurations

Add a new Application configuration from the symbol +. Enter the relevant class and module names as shown below.

kotlin android studio set configurations

Select Class and Module Name

Our Kotlin application is now ready to run. You can perform the same operation to create a build configuration for the Java application.

Kotlin for Android Studio 3.0

Kotlin plugin is already present in Android Studio 3.0. You just need to select “Include Kotlin Support” whilst creating a new project to have Kotlin configured throughout the project.

This brings an end to brief introduction of Kotlin programming language. There’s a lot of exciting stuff to do in Kotlin. We’ll be taking them one at a time. Stay tuned!

Comments

  1. Skype Customer Service says:

    kotline comes to the market for the developers, it is a development language but it cant spread hugely. so the developer has to move to the Java language but this language is very much helpful for the developer.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages