Android Kotlin - Hello World - Part One

In this article, you will learn how to create your first Android app (Hello World app) using Android Kotlin.

Introduction

Kotlin is a new programming language developed by JetBrains that runs on Java Virtual Machine (JVM). Google announced Kotlin as its official programming language for Android app development.

Advantages of Kotlin

  1. It is highly compatible so that apps that are built with Kotlin, will run on all Android devices (older devices as well).
  2. Apps developed in Kotlin are faster than the apps developed in Java. Also, Kotlin supports lambda expressions, this makes apps faster.
  3. It supports all the Android libraries, like Volley API, Retrofit, etc.
  4. It is easy to learn for Java developers. Also, the existing Java code can be easily converted into Kotlin.
  5. Compilation time is very fast as compared to Java.

Let’s get started with creating a new Android App using Kotlin.

Step 1

Create a new project. In Android Studio, go to File >> New >> New Project. Give the application a name, company domain, specify its location, and finally, the most important thing, select "Include Kotlin support".

Kotlin

Click "Next". Select target devices. I have set API version to 15.

Kotlin

Click "Next". Select an "Empty Activity".

Kotlin

Step 2

You have created your application. Now, in the Project Solution Explorer, you’ll see MainActivity.kt with its activity_main.xml inside  the layout folder.

Kotlin

Code snippet

  1. class MainActivity : AppCompatActivity() {  
  2.   
  3.     override fun onCreate(savedInstanceState: Bundle?) {  
  4.         super.onCreate(savedInstanceState)  
  5.         setContentView(R.layout.activity_main)  
  6.     }  
  7. }   

We have a TextView; let's change the default text “Hello world” to some other text in activity_main.xml.

Kotlin

Code snippet

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="com.example.kotlin_helloworld.MainActivity">  
  8.   
  9.     <TextView  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="Hello Kotlin, this is first kotlin app!"  
  13.         app:layout_constraintBottom_toBottomOf="parent"  
  14.         app:layout_constraintLeft_toLeftOf="parent"  
  15.         app:layout_constraintRight_toRightOf="parent"  
  16.         app:layout_constraintTop_toTopOf="parent" />  
  17.   
  18. </android.support.constraint.ConstraintLayout>   

Step 3

Now, we are ready to run our application. Press Shift+ F10 to run the application.

Kotlin

You can get this project here on GitHub.

That’s it.