Kotlin Cheatsheet: Scope Functions (let, run, apply, also, with)

sy is typing
Nov 6 · 1 min read

Note: this can be omitted.

There are recommended use-cases for each scope function but at the end of the day, choose the function that returns you the correct output and fits your code convention.

apply

Useful for:

  • configuring an object:

run

Useful for:

  • configuring an object and computing the result:
  • grouping several statements into an expression: run has a non-extension form too:

also

Useful for:

  • doing additional effects involving the object:

let

Useful for

  • executing a lambda on non-null objects:
  • introducing an expression as a variable in local scope:

with

Useful for:

  • grouping function calls on an object. Similar to run but not an extension:

Don’t Code Me On That

Code fragments and comments

sy is typing

Written by

Don’t Code Me On That

Code fragments and comments

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade