Learning Kotlin for Android development - Part 1

Learning Kotlin for Android development - Part 1

A guide focused on teaching you basics of Kotlin just for Android development.

Kotlin for Android

Kotlin is a fully-fledged language like any other. It is a language that compiles into Java bytecode, which means it can run on any platform capable of running Java. It is also 100% interoperable with Java, which means you can use any Java libraries in Kotlin. If you are a web developer, you can roughly think of Kotlin as Typescript and Java as Javascript.

In this particular article we assume you have some experience with Java and Android development and teach you only enough basics that are needed to write some basic Android apps using Kotlin. That way you can get your hands dirty and learn more advanced concepts.

Why Kotlin ?

Why is Java not sufficient ? Why do we need a new language that is basically compiled into Java bytecode ? The answer to this question is not without controversy. Java is a very mature and widely understood language. Yet, Android developer have complained about Java as a language of app development for the following reasons.

Java is too verbose, Kotlin is concise

Java code is quite verbose and can be difficult to read and write. This complexity increases when attempting to modify someone else's code or refactor existing code. On the other hand, Kotlin is extremely concise, making it easier to read and write.

Kotlin is safer

Java is primarily used for backend services, where issues like null pointer exceptions can be fixed quickly and changes can be rolled out. However, apps are different. It takes days or weeks for changes to roll out, and if there's an exception causing your app to crash, it can be extremely costly. Kotlin offers several language features that make it easier to detect such issues during code writing, thanks to concepts like null safety.

Kotlin's support for concurrency is simpler and better

In apps concurrency is important. You might have to show a spinner while your app fetches data from remote server. While Java does support this, Kotlin's coroutines support this sort of code in much better way. We will see this shortly.

Learning Kotlin basics

Like Java Kotlin files start with a package name and import statements. Remember you can import any java library in Kotlin.

package my.demo

import kotlin.text.*

// ...

Like Java's main function Kotlin too has a main function.

fun main() {
    println("Hello world!")
}

If you want to write your own function then this is the syntax.

fun sum(a: Int, b: Int): Int {
    return a + b
}
// Or a simpler syntax 
fun multiply(a:Int, b:Int) : a * b

Note: Semicolons in Kotlin are optional.

Variables

Kotlin has a very typescript like variable system.

val a: Int = 1  // immediate assignment
val b = 2   // `Int` type is inferred
val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment

Or for variables that get reassigned.

var x = 5 // `Int` type is inferred
x += 1

Note: You should always use val wherever possible.

Classes in Kotlin

Kotlin provides a very simplified syntax to define classes. Unlike in Java, you do not have to define separate constructors in Kotlin. You can make properties definition part of class declaration as follows.

class Rectangle(val height: Double, val length: Double) {
    val perimeter = (height + length) * 2
}

Above is the definition of class named Rectable which has two properties that are passed as part of constructor and third property that is derived.

val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")

Inheritance

open class Shape

class Rectangle(val height: Double, val length: Double): Shape() {
    val perimeter = (height + length) * 2
}

Here Rectangle inherits from Shape using : syntax. Just like Java Kotlin does not support multiple inhertiance.

Collections

One of the most important feature of Java has been its amazing collections API such as lists and maps. Kotlin makes collections first class citizens. You can define lists and maps very easily in Kotlin.

val list = listOf("a", "b", "c") // Read only list. 
val map = mapOf("a" to 1, "b" to 2, "c" to 3) // Read only map. 

println(map["key"]) // Access map value. 
map["key"] = value

// Traverse a map or list 
for ((k, v) in map) {
    println("$k -> $v")
}

Extension methods

One of the critical feature of Kotlin is that you can add methods to existing classes. For example you can add a method to String class.

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

Creating objectis without classes

Kotlin allows you to create objects of their own type without actually defining any underlying class. These are called singleton objects.

object Resource {
    val name = "Name"
}

Null safety

Kotlin provides concise syntax to check for null values.

val files = File("Test").listFiles()

// For simple fallback values:
println(files?.size ?: "empty") // if files is null, this prints "empty"

// To calculate a more complicated fallback value in a code block, use `run`
val filesSize = files?.size ?: run {
    val someSize = getSomeSize()
    someSize * 2
}
println(filesSize)

Note that ? operation tells you that the value might be null and does not call any subsequent methods if the value is null and directly skips to "?:" block.

Codelabs

Google has some helpful hands on codelabs you can play with to understand these basic concepts.

Conditionals Codelab ↗

Nullability Codelab ↗

Classes and Objects ↗

Functions and Lambdas ↗

Conclusion

What you have learned here is sufficient to start writing a basic first app. We will teach you about more advanced concepts like co-routines as well in due time. But if you know Java these concepts should be simple for you to understand.

Did you find this article valuable?

Support Android Authority by becoming a sponsor. Any amount is appreciated!