Learn Kotlin Β· 11/18

Scope Functions: Writing Idiomatic Kotlin

7 min read

Scope Functions: Writing Idiomatic Kotlin scope

Imagine you're a talented artist 🎨, and you have a beautiful canvas in front of you (that's your object in Kotlin). Now, you want to perform a series of actions on this canvas – maybe sketch an outline, add some colors, and then frame it. Instead of picking up and putting down your tools for each step, what if you could enter a special "art zone" where all your actions are directly applied to the canvas? That's precisely what Kotlin's scope functions offer for your objects!

The Problem:

In programming, we often need to perform a sequence of operations on an object. Without scope functions, this can lead to repetitive and less readable code. For instance, to configure a Robot object, you might write something like this:

kotlin
class Robot {
    var name: String = ""
    var speed: Int = 0
    fun start() { /* ... */ }
}

val myRobot = Robot()
myRobot.name = "Optimus"
myRobot.speed = 5
myRobot.start()

Notice how we have to repeat myRobot for every single operation? It's like saying, "My Robot's name is Optimus. My Robot's speed is 5. My Robot, start!" A bit wordy, isn't it?

The Solution: Scope Functions!

Scope functions in Kotlin provide a way to execute a block of code within the context of an object. This creates a temporary scope where you can access the object's properties and functions without its name, making your code more concise and readable. There are five main scope functions: let, run, with, apply, and also.


πŸš€ The 'let' Function: Null Checks and Mapping

The let function is your go-to tool when you want to work with a nullable object and only execute a block of code if it's not null. It's also fantastic for transforming an object into something else.

How it solves the problem:

Remember our Robot? What if it could be null? We'd have to add null checks before every operation, which can get messy. let simplifies this beautifully.

Under the Hood:

When you use let, the object it's called on becomes available inside the lambda as a parameter, which is conventionally named it. The let function then returns the result of the last expression in the lambda.

Example: The Null-Safe Sidekick

kotlin
var robot: Robot? = Robot()

robot?.let {
    it.name = "Bumblebee"
    it.speed = 10
    it.start()
    "Robot is configured and started!" // This string is the return value
}

In this example, the code inside the let block will only execute if robot is not null. Inside the block, we refer to our robot object as it.

Funny Exaggeration: Think of let as a bouncer at a club. It checks if the object is null (not on the list). If it's not null, it lets the object in (it) to party inside the code block.


🎨 The 'apply' and 'also' Functions: Object Configuration

apply and also are your best friends when it comes to configuring an object. They both execute a block of code and then return the object itself, which is super handy for chaining calls.

The 'apply' Function

How it solves the problem:

Remember the repetitive myRobot from earlier? apply lets you access the members of the object directly without needing a qualifier.

Under the Hood:

Inside the apply block, the object is available as the receiver (this). This means you can call its functions and properties directly.

Example: The Instant Makeover

kotlin
val myRobot = Robot().apply {
    name = "Wall-E"
    speed = 2
    start()
}

See how clean that is? We're directly setting the name and speed as if we were inside the Robot class itself.

The 'also' Function

How it solves the problem:

also is great for performing some additional actions on an object, like logging or printing its properties, without modifying the object itself.

Under the Hood:

Similar to let, the object is available as it inside the also block.

Example: The Paparazzi

Imagine you want to create a robot and immediately announce its creation to the world.

kotlin
val myRobot = Robot().apply {
    name = "R2-D2"
    speed = 3
}.also {
    println("A new robot named ${it.name} has been created!")
}

Here, we first configure the robot using apply and then, with also, we print a message about it. The original myRobot object is what gets returned and assigned.


🎭 The 'with' and 'run' Functions: Context Switching

with and run are used when you want to execute a block of code that operates on an object and possibly returns a different result.

The 'with' Function

How it solves the problem:

with is a non-extension function that takes an object as an argument and allows you to access its members without the dot notation. It's useful for grouping a set of operations on a single object.

Under the Hood:

Similar to apply, the object is available as this inside the with block. with returns the result of the last expression in the lambda.

Example: The Master Puppeteer

kotlin
val myRobot = Robot()
val result = with(myRobot) {
    name = "Gipsy Danger"
    speed = 8
    start()
    "Configuration complete for $name" // This string is the return value
}
println(result)

The 'run' Function

How it solves the problem:

run is similar to with but it's an extension function, which means you can call it on an object using the dot notation. This also allows for safe calls on nullable objects.

Under the Hood:

Like with and apply, run makes the object available as this and returns the result of the lambda.

Example: The Versatile Actor

run can be used for object configuration and computing a result.

kotlin
val myRobot = Robot()
val status = myRobot.run {
    name = "T-800"
    speed = 7
    start()
    "Robot $name is now active."
}
println(status)

Interesting Fact: run can be seen as a combination of let and with. It behaves like with in how it accesses the object (this), but it's an extension function like let, allowing for null-safe calls.


πŸ€” Choosing the Right Scope Function

With five different scope functions, how do you pick the right one? Don't worry, it's simpler than it sounds! Here's a handy guide based on common industry practices:

Function Context Object Return Value Use Case
let it Lambda result Null checks and transforming objects.
apply this Context object Object configuration and initialization.
also it Context object Additional actions like logging or side effects.
with this Lambda result Grouping function calls on a non-null object.
run this Lambda result Object configuration and computing a result.

A Simple Analogy: The "Restaurant"

Imagine you're at a restaurant (your application).

  • let is like ordering a "surprise me" dish. You get something (it), and you decide what to do with it (the lambda result). If the kitchen is out of ingredients (the object is null), you don't get a dish.
  • apply is like customizing your pizza. You're given a pizza base (this), you add all your toppings (configure it), and at the end, you get the same pizza back, ready to eat (the context object).
  • also is like taking a picture of your food before you eat it. You have your dish (it), you do something with it that doesn't change the dish itself (take a photo), and you still have the same dish afterward.
  • with is like having a personal chef. You give them an ingredient (myRobot), and they do a bunch of things with it, then tell you what they made (the lambda result).
  • run is like being the chef yourself in your own kitchen. You have all your ingredients around you (this), you cook something, and you present the final dish (the lambda result).

Remember, while these functions can make your code more concise, overusing or nesting them can lead to code that is hard to read. The key is to use them to improve clarity and reduce repetition.

πŸ“š Extra Reading

Challenge

You are tasked with processing user data. Your goal is to implement the processUser function, which takes a nullable User object and returns a nullable UserViewModel.

You must implement the function following these specific constraints, using a single chained call of scope functions on the input user object.

  1. The entire operation must be null-safe. If the input user is null, the function must return null.
  2. Use the apply scope function to update the lastLogin property of the user to the current system time. You can get this using System.currentTimeMillis().
  3. Immediately following the update, use the also scope function to log the action. Call the provided print function with a message formatted as: "Updating user: [username]", where [username] is the user's username.
  4. Finally, use the let scope function to transform the modified User object into a UserViewModel.
    • The info property of the UserViewModel must be a string formatted as: "Username: [username], Email: [email]". If the user's email is null, use the string "N/A" in its place.
    • The lastSeen property must be a string formatted as: "Last Login: [lastLogin]", using the newly updated lastLogin timestamp.

Expected result

Your processUser function should contain a single return statement that chains the scope functions apply, also, and let on the nullable user object.

The implementation should correctly:

  • Handle a null input user by returning null.
  • Use apply to modify the user object in place, specifically the lastLogin field. Inside this block, the user object should be referenced as this.
  • Use also for the side-effect of calling the print function without altering the object. Inside this block, the user object should be referenced as it.
  • Use let for the final transformation from a User object to a UserViewModel, handling the potentially null email property as specified. Inside this block, the user object should be referenced as it.
kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.