Learn Kotlin for Android in One Day

This article is for Android developers who are familiar with Java and want to get started with Kotlin right away.

Kotlin

Coming from a Java background, I realized that Kotlin syntax is similar to Java and at the same time it can be very different. Kotlin is a very powerful language with loads of syntactic sugar, which can make you feel a bit overwhelmed.

In this article, we will cover the minimum necessary topics, that will help us get up and running with Kotlin. Without further ado, let’s get started.

Our Kotlin Roadmap

Variables

Functions

for loop, while loop and when

Null Safety

Classes(constructors, methods, inheritance)

Singleton

Interfaces

Type Casts

Exception Handling

1. Variables

To declare a variable, use the var keyword.

var username: String = "some user name"

To declare a constant, use the val keyword. val in Kotlin is same a final in Java.

val API_DELAY_CONSTANT: Int = 100

Initialize a variable to null using the “?” operator. If the “?” operator is not provided the compiler won’t allow you the assign null to the variable

Notice that, there are no getter and setter methods in our classes. Instead, we access properties of the object as follows:

An instance of Dog

var dog: Dog = Dog(0)

// Settersdog.numOfLegs = 4dog.name = "Labrador"

// Getterprintln(dog.name)

6. Singleton

The Singleton pattern in Kotlin is implemented using the “object” keyword.Coming from Java, using “object” instead of “class” appears a bit weird. You can read more about it in the official Kotlin docs:

object Singleton { var name: String = "singleton object"

fun printName() { println(name) }}

// later in the codeSingleton.nameSingleton.printName()

7. Interfaces

A basic interface in Kotlin can look like like this.

interface Named { fun bar()}

interface Person : Named { // Person inherits Named fun foo()}

class Employee() : Person { override fun bar() { // do something }

override fun foo() { // do something }}

Inheriting an interface is pretty straightforward. But passing an interface to function is a bit different. Check out this example

// A function that accepts and interface as a parameterprivate fun setEventListener(listener: EventListener) { // do something}

9. Exception Handling

Final Words

That’s it for the day. We have covered plenty of topics here. I have tried to keep this article concise and useful as much as possible. If you think, some topics have been missed and should have been covered here, do let me know.

I highly recommend checking out the below resources to learn more about Kotlin and Android.