Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Scope Functions

Kotlin Scope Functions

Scope functions are a set of small utilities provided by the Kotlin standard library; they let an object be operated on within a temporary scope and decide what the code ultimately returns.

Used well, they make code shorter and clearer; used wrong, the return value differs from expectations, one of the most common pitfalls for beginners.


What are scope functions

Scope functions are essentially ordinary functions that take a lambda; they differ in only two ways: how the object is referenced inside the lambda, and what the whole call returns.

There are two ways to reference the object: as the lambda's receiver (accessed with this), or as the lambda's parameter (accessed with it).

There are also two kinds of return value: the result of the lambda's last line, or the object itself.

Combining these two dimensions gives the five most commonly used scope functions: let, run, with, apply, and also.


Overview of the five scope functions

The table below gives an overall picture first; each one is expanded on later.

function Reference method Return Value Typical use Starting version
let it Lambda result Check a nullable object then transform it, turning the object into another value Kotlin 1.0
run this Lambda result Do a multi-step computation in the object's context and return the result Kotlin 1.0
with this Lambda result Call multiple members on the same object in sequence Kotlin 1.0
apply this The receiver itself Configure object properties then return the object Kotlin 1.0
also it The receiver itself Add logging, validation, etc. then return the object Since Kotlin 1.1
runCatching None / this Result wrapper Wrap code that may throw and handle it uniformly Since Kotlin 1.3

Two-dimensional decision matrix for scope functions: the horizontal axis is whether the receiver is it or this, the vertical axis is whether to return the lambda result or the receiver itself, the four quadrants are let, run, also, apply, with let and apply marked in the focus color

The last row, runCatching, is strictly speaking not a scope function but an exception-handling tool; because it often appears with scope functions, it's listed here too.

Mnemonic: let and also use it; run, with, and apply use this.

Those returning the lambda result are let, run, and with; those returning the receiver itself are apply and also.


let

let passes the object to the lambda as a parameter, referenced with it, and returns the result of the lambda's last line.

Its most common use is handling nullable objects with a safe call, so the lambda runs only when the object is non-null.

Example

// File path: Main.kt

fun main

(

)

{

    val site

:

String

?

=

"www.runoob.com"

   

// Only when site is non-null does the lambda run, and it is site

    site

?

.

let

{

        println

(

"Site: $it"

)

        println

(

"Length: ${it.length}"

)

   

}

    val nullSite

:

String

?

=

null

   

// Use the Elvis operator as a fallback so the expression always has a value

    val length

=

nullSite

?

.

let

{

it.

length

}

?:

0

    println

(

"Fallback length for null object: $length"

)

}

Output result:



站点:www.runoob.com

长度:14

空对象兜底长度:0

Because let returns the lambda's result, it's also often used to convert an object into another type or format.

Example

// File path: Main.kt

class

Site

(

val name

:

String

, val url

:

String

)

{

   

// Override toString to make printed output readable

    override fun toString

(

)

:

String

=

"$name - $url"

}

fun main

(

)

{

   

// let returns the lambda's result; here a string is converted into a Site object

    val site

=

"RUNOOB|www.runoob.com"

.

let

{

text

->

        val parts

=

text.

split

(

"|"

)

        Site

(

parts

[

0

]

, parts

[

1

]

)

   

}

    println

(

site

)

}

Output result:



RUNOOB - www.runoob.com


run and runCatching

run treats the object as a receiver, referenced with this, and likewise returns the lambda's result.

When the lambda repeatedly accesses the object's members, run is more convenient than let because you don't write it. every time.

Example

// File path: Main.kt

class

Site

(

var name

:

String

=

""

, var url

:

String

=

""

)

fun main

(

)

{

    val site

=

Site

(

"RUNOOB"

,

"www.runoob.com"

)

   

// run references the receiver with this, so you can write property names directly when accessing members

    val info

=

site.

run

{

        name

=

name.

uppercase

(

)

       

"$name -> $url"

   

}

    println

(

info

)

    println

(

"The object itself is also modified: ${site.name}"

)

}

Output result:



RUNOOB -> www.runoob.com

对象本身也被修改:RUNOOB

run also has a form without a receiver, used to turn several statements into a block with a return value.

Example

// File path: Main.kt

fun main

(

)

{

   

// Non-extension run: groups multiple statements into a block whose last line's value is the expression's value

    val total

=

run

{

        val a

=

10

        val b

=

20

        println

(

"Computing $a + $b"

)

        a

b

   

}

    println

(

"Result: $total"

)

}

Output result:



计算 10 + 20

结果:30

runCatching and Result

runCatching has been available since Kotlin 1.3; it wraps a block of code, returns success or failure in a Result object, and no longer throws exceptions outward.

Example

// File path: Main.kt

fun main

(

)

{

   

// "RUNOOB" is not a valid number, toInt() throws an exception caught by runCatching

    val fail

=

runCatching

{

"RUNOOB"

.

toInt

(

)

}

    println

(

"Succeeded: ${fail.isSuccess}"

)

    println

(

"Failed: ${fail.isFailure}"

)

    println

(

"Exception type: ${fail.exceptionOrNull()?.let { it::class.simpleName }}"

)

    println

(

"Safe value: ${fail.getOrNull()}"

)

    println

(

"Fallback value: ${fail.getOrDefault(0)}"

)

    fail.

onFailure

{

println

(

"onFailure received: ${it::class.simpleName}"

)

}

    val ok

=

runCatching

{

"100"

.

toInt

(

)

}

    ok.

onSuccess

{

println

(

"onSuccess received: $it"

)

}

}

Output result:



是否成功:false

是否失败:true

异常类型:NumberFormatException

安全取值:null

兜底取值:0

onFailure 收到:NumberFormatException

onSuccess 收到:100

Common Result methods are isSuccess, isFailure, getOrNull(), getOrDefault(), exceptionOrNull(), onSuccess(), and onFailure().

Note:runCatching catches Throwable, including a coroutine's CancellationException. Using it inside coroutines swallows cancellation signals, so use it with care.


with

with is not an extension function; it puts the receiver in parentheses, uses this inside the lambda, and returns the lambda's result.

It suits doing several things in a row to an existing object, and the code reads like ordinary sequential logic.

Example

// File path: Main.kt

fun main

(

)

{

    val builder

=

StringBuilder

(

)

   

// with takes builder as the receiver, so you can call its methods in sequence

    val text

=

with

(

builder

)

{

        append

(

"Runoob"

)

        append

(

" - "

)

        append

(

"www.runoob.com"

)

        toString

(

)

   

}

    println

(

text

)

    println

(

"builder is also modified: $builder"

)

}

Output result:



Runoob - www.runoob.com

builder 也被修改:Runoob - www.runoob.com

with's receiver can't be null; if the object may be null, check it first or use ?.run instead.


apply

apply references the receiver with this but returns the receiver itself, not the lambda's result.

This makes apply the first choice for configuring objects: set properties inside the braces, and the whole expression evaluates to the configured object.

Example

// File path: Main.kt

class

Site

{

    var name

:

String

=

""

    var url

:

String

=

""

    var visits

:

Int

=

0

    override fun toString

(

)

:

String

=

"Site(name=$name, url=$url, visits=$visits)"

}

fun main

(

)

{

   

// apply returns the receiver, so after the braces you get the configured Site object

    val site

=

Site

(

)

.

apply

{

        name

=

"RUNOOB"

        url

=

"www.runoob.com"

        visits

=

100

   

}

    println

(

site

)

    println

(

"Type is still Site: ${site::class.simpleName}"

)

}

Output result:



Site(name=RUNOOB, url=www.runoob.com, visits=100)

类型仍是 Site:Site

Because it returns the object itself, apply is also often used to run initialization logic right after creating an object.


also

also has been available since Kotlin 1.1; it references the receiver with it and returns the receiver itself.

Its only difference from apply is how it references the object, so it's better for additional operations unrelated to object configuration, such as logging or argument validation.

Example

// File path: Main.kt

fun main

(

)

{

   

// also returns the receiver, so you can keep chaining

    val sites

=

mutableListOf

(

"Runoob"

,

"RUNOOB"

)

        .

also

{

println

(

"Created, element count: ${it.size}"

)

}

        .

also

{

it.

add

(

"www.runoob.com"

)

}

    println

(

sites

)

}

Output result:



创建完成,元素个数:2

[Runoob, RUNOOB, www.runoob.com]

Putting also in the middle of a chain lets you observe the value at each step without breaking the chain.


Decision table for choosing

For a concrete scenario, just choose according to the table below.

Requirements Recommended function Reason
Get the lambda's result, referring to the object with it let Returns the lambda result, and it is less easily confused with an outer this
Get the lambda's result, referring to the object with this run / with this makes it easy to call object members directly
Return the object itself, configuring properties with this apply Returns the receiver, good for chained configuration
Return the object itself, doing additional operations with it also Returns the receiver, with clear it semantics
Uniformly handle code that may throw and get a result runCatching Returns a Result wrapper without interrupting the flow

One more rule of thumb: if a function returns the receiver, its value lies in not breaking the chain; if it returns the lambda result, its value lies in converting the object into another value.


Common misuses

The following three problems appear most often in real code; before writing, think clearly about what is returned.

Treating apply's return value as the lambda's result

apply returns the receiver, so the code below doesn't get an uppercase string.

Example

// File path: Main.kt

fun main

(

)

{

   

// Not recommended: you might think the result is "RUNOOB", but apply actually returns the original string

    val wrong

=

"runoob"

.

apply

{

uppercase

(

)

}

    println

(

wrong

)

   

// Recommended: use let or run when you need to transform the result

    val right

=

"runoob"

.

run

{

uppercase

(

)

}

    println

(

right

)

}

Output result:



runoob

RUNOOB

uppercase() inside apply does execute; only its return value is discarded, because apply cares only about the object itself.

it is shadowed in nested calls

When you nest two scope functions that use it, the inner it shadows the outer one; the code compiles but is easy to misread.

Example

// File path: Main.kt

fun main

(

)

{

    val words

=

listOf

(

"runoob"

,

"kotlin"

)

   

// Not recommended: both levels use implicit it, and the inner it shadows the outer it

    val bad

=

words.

map

{

it.

let

{

it.

uppercase

(

)

}

}

    println

(

bad

)

   

// Recommended: name the inner parameter explicitly so the semantics are clear

    val good

=

words.

map

{

word

->

word.

let

{

text

->

"[$text]"

}

}

    println

(

good.

joinToString

(

)

)

}

Output result:



[RUNOOB, KOTLIN]

[runoob], [kotlin]

Another approach is to change one level to a this-form run, so it won't conflict.

Forgetting the safe call on a nullable object

Scope functions don't handle null themselves; a nullable object must be null-checked first or use ?.

Example

// File path: Main.kt

class

Site

(

val name

:

String

)

fun main

(

)

{

    val nullSite

:

Site

?

=

null

    val realSite

:

Site

?

=

Site

(

"RUNOOB"

)

   

// Compile error: you can't call a scope function directly on a nullable type

   

// nullSite.let { println(it.name) }

   

// Correct: use a safe call; when the object is null the whole call is skipped

    nullSite

?

.

let

{

println

(

"Won't execute: ${it.name}"

)

}

    realSite

?

.

let

{

println

(

"Executed: ${it.name}"

)

}

    realSite

?

.

also

{

println

(

"also works with a safe call: ${it.name}"

)

}

}

Output result:



执行了:RUNOOB

also 也能配合安全调用:RUNOOB


Common questions

The following questions come up most often when choosing a scope function.

Both let and run return a result; how to choose

It depends on whether the lambda needs frequent access to object members. If so, use run (this); otherwise use let (it), which is safer when nested.

Both apply and also return the object; how to choose

Use apply for configuring properties, since this is more natural when writing properties; use also for added operations and logging, since it won't be confused with an outer this.

What's the difference between with and run

They're almost the same functionally; the difference is the call form: with(obj) { } is a normal call, while obj.run { } is an extension call that can combine with ?. to handle nulls.

Do scope functions affect performance

The five common functions are all inline, so the lambda creates no extra function object and the runtime overhead is negligible.