Dec 7, 2023

Learning Kotlin for Android development - Part 1

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

Learning Kotlin for Android development - Part 1

Kotlin for Android

Kotlin is a full 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 development you can roughly think about Kotline 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 very verbose and is harder to read and write. This becomes complex when you are trying to modify someone else's code or refactor existing code. Kotlin on other hand is extremely concise and hence easier to read and write.

Kotlin is safer

Java is primarily used for backend services where if you discover any issue such as a null pointer exception you can fix it quickly and roll out the changes. Apps are different. It takes days or weeks for the changes to rollout and hence if there is an exception that cause your app to crash, it can be extremely costly. Kotlin has several language features that make it easier to detect such issues when writing code through 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.

Continue Reading
Learn about other front end technologies

Learn about other front end technologies

We are partnering with Frontendeng.dev to cross promote the content around front end engineering.

Published Dec 12, 2023

Android paired with Windows Laptops

Android paired with Windows Laptops

The new trend is to build Android and Windows Laptop into one hardware.

Published Jan 11, 2024

What are co-routines in Kotlin ? Kotlin for Android Part -2

What are co-routines in Kotlin ? Kotlin for Android Part -2

In this part we will learn about Kotlin's co-routines. It is an important concurrency design pattern that is extremely useful when designing asynchronous programs.

Published Dec 31, 2023

Backends for your Android App

Backends for your Android App

In this article, we will explore the various options available for app developers who are primarily focused on building an app backend.

Published Jan 1, 2024

Google Flutter vs Android Jetpack Compose : A detailed comparison

Google Flutter vs Android Jetpack Compose : A detailed comparison

Flutter code looks remarkably similar to Android Jetpack Compose. However which one of them is better ? We find out in this article.

Published Jan 11, 2024

Minimal starting template for Android Compose

Minimal starting template for Android Compose

Find a simple minimal code to open an app with top and bottom bar. Find full code on https://github.com/Wiseland-Inc/dev.androidauthority.app

Published Dec 11, 2023

Spring Boot for App Backends

Spring Boot for App Backends

Simple spring boot template to deploy on Google Cloud and to be used as your app backend.

Published Jan 6, 2024

Making android development less painful

Making android development less painful

Android development has always been challenging and frustrating right from start. However things are looking better now.

Published Dec 4, 2023

Understanding Layouts in Android Compose

Understanding Layouts in Android Compose

A very quick tutorial on compose and layouts.

Published Dec 10, 2023

What are adaptive android apps ?

What are adaptive android apps ?

Adaptive apps are app equivalent of responsive web apps. Apps that resize to give good user experience across several devices.

Published Dec 9, 2023