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

var myString: String? = null

Define a static variable using companion object.

class Animal {



companion object {

const val DEFAULT_NUM_OF_EYES = 2

}

}



animal.numOfEyes = Animal.DEFAULT_NUM_OF_EYES

Initialize a variable later in the code using lateInit keyword.

lateinit var user: User // Initialized later in code

lateinit var items: List<String> // Initialized later in code

2. Functions

A simple function in Kotlin looks like this.

fun getNumber(): Int {

return 1

}

getNumber() is a function whose visibility is public, takes no parameters and returns an Int

Let’s try creating a private function with multiple parameters.

private fun getStringLength(str1: String, str2: String): Int {

return str1.length + str2.length

}

getStringLength() is a function whose visibility is private, takes two parameters and returns an Int

How about a static function?

class MyStringUtil {



companion object {

fun getOddLengthString(str: String): String? {

if (str.length % 2 == 0) return null



return str

}

}

} var str: String = MyStringUtil.getOddLengthString("hey")

getOddLengthString() is a static function that takes a parameter, returns a String. The return type has “?” in front of it. This is to specify that the function can return a null.

3. For loop, while loop and when

A for loop in Kotlin uses “in” keyword to access items in a collection.

var items: List<String> = ArrayList<String>()



for (item in items) {

// do something with item

}

You can also access the indices of items in a for loop.

for (index in items.indices) {

// access items using index

// items.get(index)

}

A while loop in Kotlin is same as a while in Java. Nothing new there :)

var i: Int = 0 // Some while loop

do {

// do something

i++

} while (i < 5) // Another while loop

while (i < 10) {

// do something

i++

}

However, the switch statement in Java has been made simpler. Kotlin uses when keyword to switch between multiple conditions and its so much more powerful and concise.

// A cool example of when statement

fun describe(obj: Any): String? {

var res: String? = null



when (obj) {

1 -> { res = "One" } // if obj == 1

"Hello" -> res ="Greeting" // if obj == "Hello"

is Long -> "Long" // if obj is of type Long

!is String -> "Not string" // if obj is not of type String

else -> {

// execute this block of code

}

}



return res

}

4. Null Safety

In Java, to avoid a NullPointerException we can use a “if” block. For eg.

if (person != null && person.department != null) {

person.department.head = managersPool.getManager()

}

But in Kotlin, we can skip the “if” block and re-write our code like this.

// If either `person` or `person.department` is null, the function is not called:

person?.department?.head = managersPool.getManager()

“?.” is known as the safe call operator and the above example show it can be used in chains. This helps us write clean, simple code and avoid NPE at the same time.

In case, you want to handle a scenario where the object is null, you can use the “?:” a.k.a the Elvis operator.

var name = person?.name ?: throw InvalidDataException("Person cannot be null.")

5. Classes (constructors, methods, inheritance)

A simple example of class in Kotlin can look like this. The “open” keyword specifies that the class can be inherited. A class that is not “open”, is as good as a final class in Java.

open class Animal {

// This class is open and

// can be inherited

}



class Dog : Animal() { // Notice the paranthesis

// Class dog is final and

// can't be inherited

} // Compiler throws error

class Labrador : Dog {



}

Below is a more involved example of a class and inheritance in Kotlin.

Example of classes in Kotlin

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) // Setters

dog.numOfLegs = 4

dog.name = "Labrador" // Getter

println(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 code

Singleton.name

Singleton.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 parameter

private fun setEventListener(listener: EventListener) {

// do something

} // Passing an interface to the function

setEventListener(object : EventListener{

override fun call() {

// do something

}

})

8. Type Casts

To check if a an object is an instance of a particular class we use the “is” and “!is” operator.

if (obj is String) {

print(obj.length)

}



if (obj !is String) {

print("Not a String")

}

To avoid an exception being thrown, one can use a safe cast operator “as?” that returns null on failure. This is what is called safe typecast in Kotlin.

val x: String? = y as? String

In this case, if there is a failure in type casting, null is returned and throwing an exception is avoided.

9. Exception Handling

Throwing and handling an exception is pretty much the same as in Java.

throw Exception("Hi There!") try {

// some code

}

catch (e: SomeException) {

// handler

}

finally {

// optional finally block

}

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.

Till then! Keep learning and Happy Coding!