Let’s discover Kotlin — Part 3

Nazim Benbourahla
2 min readJun 30, 2017

Before you start reading this article, you may start by reading the first part: “Let’s discover Kotlin — Part 2

Nullable

In Kotlin, you can specify if a variable is null with “?” operator.

For example, imagine a function that return a “User” and this user can be null. In this case, you can just put a “?” in the return type of the function

fun getCurrentUser(): User? {
// ...
}

If you use the return type of this function to access some data, without checking the nullability, the Intellij will display an error message

You have many ways to handle the nullability of a variable.

You can check manually the nullability and then use the variable. The operator “!!” is used to specify that you are sure that this variable is not null.

if (getCurrentUser() != null) {
getCurrentUser()!!.login
}

Or using the “?” operator to do all things in a safe way

getCurrentUser()?.login

If “getCurrentUser” returns null, the “login” field will also returns null.

You can also use let block to execute some code, only if the “getCurrentUser” is not null.

// prints user only if current user is not null
getCurrentUser()?.let { println(user) }

Extensions

Kotlin provide the ability to extend a class with new functionality without having to inherit from a class (see design pattern Decorator)

Let’s take our User class from the previous article :

class User(var login: String, var password: String) {
var isSafePassword: Boolean = false
get() {
return password.length > 7
}
}

We can add a method to clear the user state, without updating the User class:

fun User.clear() {
this.login = ""
this.password = ""
this.isSafePassword = false
}

We create a function clear, this function will be available if you have a instance of a User. For example :

user.clear()

Extension are solved statically, you are not adding functions to a class but make function callable from an instance of this class.

Let’s take another example. Suppose we want to add to the String class a method that tells us whether a string’s length is longer than a given length.

fun String.isStringLongerThan(length: Int) : Boolean {
return this.length > length;
}

And use it easily

getCurrentUser()?.password.isStringLongerThan(7)

I hope you enjoyed this third part of these tutorials about Kotlin, the next ones are coming soon.

--

--