🐦 Kotlin Beginner

What does the with scope function do in Kotlin?

Answer

The with function takes an object and a block, makes the object available as this inside the block, and returns the block's result. Unlike the other scope functions, with is not an extension function — it is called as a regular function: with(user) { println(name); println(age) }. It is best used when you want to call multiple methods on a non-nullable object without repeating its name. The main difference from run is syntactic — with is preferred when the object is passed as an argument rather than chained.