From Java to Kotlin:

Boonya Kitpitak
The OOZOU Blog
Published in
3 min readJul 14, 2017

Make things easier with “let” and “apply” (Android)

“let” and “apply” are very useful functions in Kotlin. It could change the way you write your code from what you did in Java. In this article, I would like to share how to make your code easier with “let” and “apply”. I will assume that your have some basic knowledge about Kotlin.

What can “let” do ?

I would like to point out two main usages of “let”

  1. Scoping Function: “let” could be used to make your code self-contain in “let” block and keep the logic separate. The variable in front of “let” could be referred to as it. Look at the code below as an example.

As you can see that the File(“dummy.txt”) will only be visible in the “let” block

2. Check against null: In Java, to prevent our lovely NullPointerException we have to repeatedly check for null in our code. Fortunately, we could make things easier with “let”. We can make the “let” block execute only when variable is not null. Let’s see an example.

Suppose we have object like this

user -(hold)-> info -(hold)-> email

Both user and info could be null. This is how we would do this in Java.

And in Kotlin :)

As you can see that it’s much shorter and cleaner in Kotlin

How to use “apply” ?

“apply” may help you write the code in slightly different way

“apply” can be used as extension on all type of variables. It will return the object with the thing in “apply” block apply to the object (it works according to its name). Let’s see things in action to get clearer picture.

Here are a couple of examples:

  1. In Java, when we try to set up RecyclerView. We might do something like this.

With “apply” in Kotlin, we could make it this way.

2. Creating object through setter in Java might require something like

With “apply” we could make things slightly better

Inside “apply” block we can refer to “properties” or “methods” of the variable that used “apply” with out having to refer to that variable again.

Conclusion

In my opinion “let” does make the code shorter and cleaner, especially the ability to check against null. Since as an Android developer we all might have to write many lines of code to check for null values in Java to prevent NullPointerException and “let” does solve that pain. For “apply”, I think it helps avoiding repeatedly referencing to the same variable and makes the code a bit easier to read.

Thank you for reading. This is my very first article. Therefore, if there are any mistakes or the things I can improve about my article please leave comments. :)

Reference

--

--

Boonya Kitpitak
The OOZOU Blog

Android Developer at Oozou. Also Guitarist and Headbanger