Make things easier on Android with “let” and “apply”

“let” and “apply” are very useful functions in Kotlin. It could change the way you write your code from what you did in Java


“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 you 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 the 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.

File("dummy.txt").let {
  print(it.toString())
}
//File "dummy.txt" is not visible here

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 the variable is not null. Let’s see an example.

Suppose we have an object like this

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

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

if(user != null) {
  Info info = user.getInfo();
  if (info != null) {
    String email = info.getEmail();
    if(email != null) {
        sendEmailToUser(email)
    }
  }
}

And in Kotlin :)

user?.info?.email?.let? {
    sendEmailToUser(it)
}

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


ow to use “apply”?


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

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

Here are a couple of examples:

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

recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new YourRecyclerViewAdapter(this));
recyclerView.setHasFixedSize(true)

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

recyclerView.apply {
  layoutManager = LinearLayoutManager(this@YourActivity)
  setHasFixedSize(true)
  adapter = YourRecyclerViewAdapter(this@YourActivity)
}

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

User user = new User();
user.setFirstName = "John";
user.setLastName = "Doe";
user.setGender = "Male";
user.setProfileUrl = "...";
user.setPhoneNumber = "...";

With “apply” we could make things slightly better

User user = User().apply {
  firstName = "John"
  lastName = "Doe"
  gender = "male"
  profileUrl = "..."
  phoneNumber = "..."
}

Inside “apply” block we can refer to “properties” or “methods” of the variable that used “apply” without 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 to avoid repeatedly referencing the same variable and makes the code a bit easier to read.


Reference

Like 160 likes
Ben Kitpitak
Mobile Developer at OOZOU in Bangkok, Thailand
Share:

Join the conversation

This will be shown public
All comments are moderated

Get our stories delivered

From us to your inbox weekly.