Newer Post

X-Outpost: Spain

Older Post

Using Firebase Analytics with Android (Kotlin)

Kotlin Basics: Thinking Functional

Hey! If you are here you are either an Android developer, you are seeking to learn more about functional programming, or you are just a curious guy that heard about the Kotlin hype 😄 and would like to learn more about it.

This article assumes that you have no knowledge of Kotlin at all 🤓, so prepare to be taken from zero through the essential topics. Hopefully, by the end of this article, you will have the tools and skills to start playing and having lots of fun.

What Is Kotlin?

Kotlin

Kotlin is a statically typed programming language which runs in the JVM but can also be used to compile Javascript or use the LLVM infrastructure to compile native code. Kotlin is a free and open source project under the Apache 2.0 license. Its development and distribution as free software are secured by the Kotlin Foundation.

It doesn’t have the same syntax as Java, but it was designed to interoperate with Java, which is very useful for Android developers. This allows migrating the code to Kotlin gradually.

A Functional Mindset

Something important to take in consideration when learning Kotlin is to understand the functional programming rules. So let’s briefly explain how it works:

It is a programming paradigm based on the use of mathematical functions. It’s basically the process of building software by composing pure functions, avoiding mutable data and side effects. Functional programming is declarative rather than imperative.

To understand the declarative vs imperative programming, I have found this good metaphor here:

Declarative Programming is like asking your friend to draw a landscape. You don’t care how they draw it, that’s up to them.

Imperative Programming is like your friend listening to Bob Ross tell them how to paint a landscape. While good old Bob Ross isn’t exactly commanding, he is giving them step by step directions to get the desired result.

Ok, ok, I know what you are thinking… Enough talking; show me the code! 👨🏽‍💻

What does Kotlin code look like? 🧐🤔

The official documentation has a great graphic that briefly shows how it looks:

Code Sample

If you have some experience with Java in Android, you will feel very familiar with this example, and that’s an excellent reason not to feel afraid of learning Kotlin.

Now, let’s cover some of the basic syntax, so you get ready to tackle your next project with Kotlin. 😎

Defining Functions

When you define a function, you start it with the keyword fun. Here’s an example from the Kotlin documentation which has two Int parameters and an Int return type:

fun sum(a: Int, b: Int): Int {
    return a + b
}

As you see, the way of specifying the arguments is name: type, and you specify the return type by putting a colon after the function parentheses and then the type.

Our function can also have the return type inline, which implicitly sets the return type:

fun sum(a: Int, b: Int) = a + b

We will, of course, want to have a function with no return type specified:

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

You may have looked at then return type in the example above which has Unit in it. This type corresponds to the void type in Java, but in Kotlin, it can be omitted, like this:

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

Defining Variables

I made a couple of examples using the online Kotlin Playground, the first example shows how to define an immutable variable:

val age:Int = 14 // type explicitly specified

val floor = 3 // implicity type

val year: Int
year = 2018

As you see, there’s more than one way of defining a variable; Just take in consideration that if you don’t assign a value to the variable, you need to specify the type.

If you want to make it mutable, just use the keyword var instead:

var year:Int
year = 2018
year = 2017

Dealing with String Building

One common need of developers is to build strings out of some values to create sentences with the variables in them. In kotlin we have string templates. We specify the variable name preceded by a $ inside of the quotes, for instance:

val age = 21
val s1 = "I am $age years old"

You can also perform some inline operations on the variable in the template:

val s2 = "${s1.replace("am", "was")}, but now I am $age years old"

By default, the variables in Kotlin are non-nullable. That means that they don’t allow null values. If you need your variable to allow null values, you have to add a ? after the type, for instance:

var name:String? = null

Conditional Expressions

There’s not a lot of new things to learn here. It looks pretty much like what we are used to seeing when programming in Java, C#, Javascript, or any other traditional language. A slight difference that we will learn here is how we can use if as an expression, which is an alternative to the shorthand if in other languages.

Just for the sake of following the examples, I’m adding one:

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

It’s pretty much like Java. Here is the second example, using an if as an expression and have it set to the return statement of a function:

fun maxOf(a: Int, b: Int) = if (a > b) a else b

There’s always room for improvement. One of Kotlin’s goals is to reduce boilerplate and allow the developer to write code as readable as possible.

Null Safety

Ok, now let’s talk about one of my favorite topics in Kotlin - how to ensure the object I am accessing is not null. As per the documentation: “Kotlin's type system is aimed at eliminating the danger of null references from code, also known as The Billion Dollar Mistake.”

Kotlin limit the possibilities of a NullPointerException happening to:

  • An explicit throw of a NullPointerException()
  • Using the force-unwrapping !! on a null object.
  • An uninitialized this passed and used somewhere else

If you define a non-nullable variable and try to set it to a null value, you will get a compile-time error. Here’s an example of both nullable and non-nullable cases:

var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
print(b)

So, let’s see how Kotlin approaches to solve this. Using the examples above, we can say that we can call any method or property on the variable a safely, but we can’t ensure the same for the variable b. We need to manage the null-case, so our app does not crash. 💣

We have more than one way to assert the value is not null. If you are a Java developer, the first thing that comes to your mind is probably something like this:

val b = "Kotlin"
if (b != null && b.length > 0) {
    print("String of length ${b.length}")
} else {
    print("Empty string")
}

And Kotlin will allow this. But… I will tell you a prettier and more idiomatic way to deal with these cases: The one and only safe call operator ?.

Using the safe call operator, we can access all the properties in an object. It will pass only if the value is not null.

val a = "Kotlin"
val b: String? = null
println(b?.length)
println(a?.length)

You can use it at many levels of properties deep:

bob?.department?.head?.name

An expression like this returns a nullable. It will be null if it fails at any point. Otherwise, it will have a value. So, what if I want it to be non-nullable?

In that case, you can set a default value using an Elvis-operator ?:. If you're wondering why it's named like that, just flip your head and you will see the top of Elvis Presley’s head. 🕺😂

var name:String?
name = null

val length = name?.length ?: 0

In this example, we are trying to get the length property of the nullable variable name. If it returns null, it will default to 0.

Wrap-Up

Intense! We covered some of the most basic Kotlin topics, and in a future article, we will dive into some other basic and not-so-basic stuff.

Meanwhile, you can practice your Kotlin knowledge in the Kotlin Playground/ It’s online, free, and very easy to use!

See you in the next one! 😎

We'll help you unleash.

Join the 30,000 developers who subscribe to our newsletter.

Scale your
Development team

We help you execute projects by providing trusted developers who can join your team and immediately start delivering high-quality code.

Hire Developers
code, kotlin