
Kotlin Scope Functions: let, run, with, apply, also — Complete Guide
Kotlin Scope Functions: let, run, with, apply, also — Complete Guide Kotlin's scope functions are powerful tools that let you execute code blocks in the context of an object. They make your code more concise and readable. Let's master all five! The Five Scope Functions at a Glance Function Receiver Return Value Best For let it Last expression Null safety checks, transformations run this Last expression Initialization + computation with this Last expression Working with object properties apply this Same object Builder pattern, fluent configuration also it Same object Side effects, logging, debugging 1. let: Null Safety & Transformations val name : String ? = "Alice" // Without let: repetitive null checks if ( name != null ) { println ( name . uppercase ()) } // With let: elegant null safety name ?. let { println ( it . uppercase ()) // it = "Alice" } // Transform values val length = name ?. let { it . length } ?: 0 Use let when: Checking null-safe operations Transforming object values A
Continue reading on Dev.to
Opens in a new tab


