Learn Android Development with Kotlin

Kotlin is a general-purpose programming language with type inference and cross-platform. It can interoperate with Java. It mainly targets the JVM but can compile JavaScript or native code too. This language is sponsored by JetBrains and Google through the Kotlin Foundation. Learn Android Development with Kotlin. Today we will learn Episode:1 and we will continue from beginning to advance.

Why use Kotlin in Android? What did happen to Java?

First of all, it is very known to us that Java is a very famous language and it is the most widely used in Android application development. Java has a huge community of its own and is capable of giving support to so many key use-cases. But it doesn’t mean that Java is always the best option available. Rather, we got more reasons to find alternative language to use. Java is old, error-prone and been slow to modernize. If we look closely, developers of OpenJDK have started to fill up the gap with Java 8. But Android still doesn’t use all the core features of Java 8. Most of the developers are still working with the old Java 7 and 6 which won’t be much different to expect in the future.

Kotlin came into this scope of developer thoughts; as it is open source and absolutely new. It is based on the Java Virtual Machine (JVM) and thus the learning curve is been not so high for the developers; especially for Android software engineers. Moreover, Google has set Kotlin as its primary and official language to develop Android application which implies to greater scope for the future.

Let’s share some better reasons to start using Kotlin into our app development.

  • Java is very error-prone where Kotlin is less. It even handles one of the biggest and most unexpected mistakes in the industry which is “nullability”. Kotlin uses basic structure to ensure null-safety which makes the language great.
  • We love to make clean and fewer codes. It’s easy to read, to understand. And obviously, less code means fewer errors. With Java, we have to write lots of code in order to achieve any simple thing done where with Kotlin, even simple things can be done in fewer lines.
  • As Kotlin is an open-source language, it is growing its own community very fast. And we know well, a bigger community is very useful for the developers.
  • Kotlin is 100% interoperable with Java which is a blessing for developers who are used to work in Java. You can call Java code from Kotlin and vice-versa seamlessly. Both Kotlin and Java generate the same bytecode.
  • Kotlin handles Null Pointer Exception (NPE) very well. It guards your code with null checks everywhere which are a time consuming and boring task. By default, all variables are non-null. If a nullable variable is needed, it needs to be marked with a “?”.
  • One will get great IDE and tooling support for Kotlin. Nothing to worry about in with continuing support, because a well-established company backs it. JetBrains has created many amazing and widely used IDEs in the world. Even if anyone wants his Java file to be converted in Kotlin, they can use the “Convert Java File to Kotlin” option from the IDE.

Steps to start developing Android applications using Kotlin?

We use Android studio IDE to develop an Android application. We will go through the steps to make a simple Android application using Kotlin in Android studio. For the steps, we can assume that you have the latest version of Android Studio and Java Virtual Machine (JVM) preinstalled on your computer.

Step 1:

Open your Android studio. At the time of writing, we are using version 3.4.2 of it. Next click on the Start a new Android Studio project.

Learn Android Development with Kotlin
Learn Android Development with Kotlin

Step 2:

Here we can choose any kind of activity to start our project. For now, we will choose “Empty Activity” as we don’t need any pre-ready component in our page. Then we will click on “Next”.

Step 3:

Now we will put our required information into the fields. Our application name will be “First Kotlin App” for now. We are keeping the package name as an example and choosing the Kotlin language as our application language. Later on, we will click on “Finish”.

Learn Android Development with Kotlin
Learn Android Development with Kotlin

Step 4:

Soon, the Gradle will start to synchronize the project materials.

Learn Android Development

Step 5:

Open the file named “MainActivity”. If we look closely, then it is visible to us the file is written in Kotlin language. Now, we are going to look over the application design. Therefore, we will open the file named “activity_main.xml”. Let’s see the codes of “MainActivity” before going there.

package com.example.firstkotlinapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?)
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)
 } 
}
Learn Android Development with Kotlin

Step 6:

This is our design file. We can put our preferred design using XML here and then inflate it. For now, the “Hello World!” is visible at the center of the page within a TextView. Let’s have a look at codes,

<?XML version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

<TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Hello World!"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintLeft_toLeftOf="parent"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
Learn Android Development with Kotlin
Learn Android Development with Kotlin

Step 7:

Now we will run the application using our physical Android device, Xiaomi Redmi Note 7 Pro. Click on “OK” now.

Learn Android Development with Kotlin
Learn Android Development with Kotlin

Step 8:

Now the application is in front of us now. This is our very first Android application written in Kotlin.

Learn Android Development with Kotlin

Syntax Changes (Java to Kotlin)

It’s time to go through some pieces of code. We will see some basic differences in coding syntax between Java and Kotlin.

Terminator of Statement

In Java, we have ‘;’ as our terminator of a statement which means, we put it at the end of every statement to mark it as complete.

//Java
  Log.d(TAG, “Hello, I am a log”);
//Kotlin
  Log.d(TAG, “Hello, I am a log”)

Thus, we are using the same statement in respectively Java and Kotlin language above.

Inheritance

We are used to with the “extend” keyword to inherit any class while writing its child class in Java. But in Kotlin, we don’t need to use the keyword. Rather we will use the “:” character to indicate the inheritance. Let’s see some codes,

// Java way to inherit the AppCompatActivity using the extends keyword
     public class MainActivity extends AppCompatActivity {}
// Kotlin way to inherit the AppCompatActivity using the : keyword
    class MainActivity : AppCompatActivity() {}

Nullable Variable

In Java, we don’t have an option to handle nullability. It is like variables in Java can contain null in common. But in Kotlin, by default, not all the variables can contain null. To assign null to a variable, we need to make it nullable by adding ‘?’ to the type of it. Let’s see some codes,

//Java way to access a UI button
    private Button mMyButton;
    mMyButton = (Button)findViewById(R.id.my_button);
    mMyButton.setText(“My Button”);

// Kotlin way to access a UI button
    private var mMyButton: Button? = null
    mMyButton = findViewById(R.id.my_button) as Button?
    mMyButton.text = “My Button”

Overridden Methods

We usually see @override annotation over overridden methods in Java (which is optional). But in Kotlin, it has been set strictly to put override before function head to ensure the method is overridden and its readability. Let’s see some codes,

//Java way to write an overridden method

     @Override
     protected void onCreate(Bundle savedInstanceState) {
  }

//Kotlin way to write an overridden method
  override fun onCreate(savedInstanceState: Bundle?) {
  }

Type Casting

We sometimes want to convert our object of a type to another type which is called typecasting. In Java, we generally use “(Casting Type)” before the object to make the typecasting. But in Kotlin, there are some changes. Kotlin has introduced a new keyword named “as” to typecast the objects. Let’s see some codes,

//Java way to typecast an object
   mMyButton = (Button)findViewById(R.id.my_button);

//Kotlin way to typecast an object
   mMyButton = findViewById(R.id.my_button) as Button?

Setting Properties to an Object

In Java, we use setter methods to set the property to objects. It is a traditional way of setting values, whereas, In Kotlin, object property can be assigned just like a variable assignment. Let’s see some codes,

//Java way to set text at a UI button
  private Button mMyButton;
  mMyButton = (Button)findViewById(R.id.my_button);
  mMyButton.setText(“My Button”);

//Kotlin way to set text at a UI button
  private var mMyButton: Button? = null
  mMyButton = findViewById(R.id.my_button) as Button?
  mMyButton.text = “My Button”

Model/Data Class

 We need to use different constructors and lots of setter-getter methods in order to achieve the proper model class in Java whereas, it can be easily achieved with fewer codes using Data class in Kotlin. Let’s see some codes,

//Java way to make a model class
 public class Student {
  private String mName, mClassName, mDepartment;
  private int mID;
  public Student(String mName, String mClassName, String mDepartment, int mID) {
  this.mName = mName;
  this.mClassName = mClassName;
  this.mDepartment = mDepartment;
  this.mID = mID;
}

public Student(String mName, String mClassName, int mID) {
 this.mName = mName;
 this.mClassName = mClassName;
 this.mDepartment = "DEFAULT";
 this.mID = mID;
 }
public String getName() {
  return mName;
  }
public void setName(String name) {
  mName = name;
  }

public String getClassName() {
  return mClassName;
  }
public void setClassName(String className) {
  mClassName = className;
  }
public String getDepartment() {
  return mDepartment;
  }

public void setDepartment(String department) {
 mDepartment = department;
 }

public int getID() {
  return mID;
 }
public void setID(int ID) {
  mID = ID;
 }
}

//Kotlin way to make a model class
   data class Student (
   var name: String,
   var className: String,
   var department: String = "DEFAULT",
   var id: Int
 )

Kotlin language brought simplicity to Android application development. We believe it is easier to learn and use. See you with more of it in the next episode. Stay with us.

2 thoughts on “Learn Android Development with Kotlin”

  1. A very good comprehensive article for making your hands dirty with Kotlin for better and organized development! Cheers

    Reply

Leave a comment