WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 11 of 100

What is the purpose of the apply, let, with, and run scope functions in Kotlin? Provide examples for each.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, scope functions are useful for performing certain operations on an object in a concise and readable way. They offer a way to simplify your code and make it more expressive.

1. ‘let‘ function:

‘let‘ is a scoping function that allows you to execute a block of code on a nullable object. It is useful to avoid using the safe call operator for every property or function call. The object is available inside the lambda as ‘it‘. At the end of the lambda, the result of the lambda expression is returned.

Example:

val name: String? = "John"
val result = name?.let {
    "Hello, $it!"
} ?: "Name is null"
println(result) // prints "Hello, John!"

2. ‘apply‘ function:

‘apply‘ is a scoping function that is used when we want to perform some operations on an object and then return the modified object. The object is available inside the lambda as ‘this‘.

Example:

data class Person(var name: String, var age: Int)
val person = Person("John", 20)
person.apply {
    age = 21
    name = "Jane"
}
println(person) // prints "Person(name=Jane, age=21)"

3. ‘with‘ function:

‘with‘ is a scoping function that takes an object and executes the given block of code with the object as its receiver. It is useful when we have to perform multiple operations on the same object.

Example:

data class Person(var name: String, var age: Int)
val person = Person("John", 20)
with(person) {
    age = 21
    name = "Jane"
}
println(person) // prints "Person(name=Jane, age=21)"

4. ‘run‘ function:

‘run‘ is a scoping function that is used when we want to perform some operations on an object and then return the result of those operations. The object is available inside the lambda as ‘this‘. It is similar to ‘apply‘, but it returns the value of the lambda.

Example:

data class Person(var name: String, var age: Int)
val person = Person("John", 20)
val result = person.run {
    age = 21
    name = "Jane"
    "Hello, my name is $name and I'm $age years old."
}
println(result) // prints "Hello, my name is Jane and I'm 21 years old."
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics