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
- It is highly compatible so that apps that are built with Kotlin, will run on all Android devices (older devices as well).
- Apps developed in Kotlin are faster than the apps developed in Java. Also, Kotlin supports lambda expressions, this makes apps faster.
- It supports all the Android libraries, like Volley API, Retrofit, etc.
- It is easy to learn for Java developers. Also, the existing Java code can be easily converted into Kotlin.
- 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".
Click "Next". Select target devices. I have set API version to 15.
Click "Next". Select an "Empty Activity".
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.
Code snippet
- class MainActivity : AppCompatActivity() {
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- }
- }
We have a TextView; let's change the default text “Hello world” to some other text in activity_main.xml.
Code snippet
- <?xml version="1.0" encoding="utf-8"?>
- <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context="com.example.kotlin_helloworld.MainActivity">
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello Kotlin, this is first kotlin app!"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintLeft_toLeftOf="parent"
- app:layout_constraintRight_toRightOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
-
- </android.support.constraint.ConstraintLayout>
Step 3
Now, we are ready to run our application. Press Shift+ F10 to run the application.
You can get this project here on GitHub.
That’s it.