Mobile Development Kotlin Subjective
Oct 04, 2025

Explain Kotlin scope functions (let, run, with, apply, also) and when to use each.

Detailed Explanation
Scope functions execute code blocks within object context with different return values and context references.\n\n**let** - Returns lambda result, context as "it":\n\nval result = person?.let {\n println("Name: ${it.name}")\n it.age * 2\n} // Returns age * 2 or null\n\n// Use case: null safety and transformations\nval length = text?.let { it.trim().length }\n\n\n**run** - Returns lambda result, context as "this":\n\nval result = person.run {\n println("Name: $name") // direct access\n age * 2\n} // Returns age * 2\n\n// Use case: object configuration and computation\nval result = service.run {\n configure()\n execute()\n}\n\n\n**apply** - Returns context object, context as "this":\n\nval person = Person().apply {\n name = "John"\n age = 30\n email = "john@example.com"\n} // Returns configured Person object\n\n// Use case: object initialization\nval intent = Intent().apply {\n action = Intent.ACTION_VIEW\n data = Uri.parse(url)\n}\n\n\n**also** - Returns context object, context as "it":\n\nval person = Person("John", 30).also {\n println("Created person: ${it.name}")\n logger.log("Person created")\n} // Returns original Person object\n\n// Use case: additional actions without changing object\n\n\n**with** - Non-extension function, returns lambda result:\n\nval result = with(person) {\n println("Name: $name")\n age * 2\n} // Returns age * 2\n\n// Use case: multiple operations on object\nwith(canvas) {\n drawCircle(x, y, radius)\n drawText(text, x, y)\n}\n\n\n**Selection guide:**\n• **let**: null safety, transformations\n• **run**: object configuration + computation\n• **apply**: object initialization\n• **also**: additional actions, logging\n• **with**: multiple operations on non-null object
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback