with function. What will be printed when this code runs?data class Person(var name: String, var age: Int) fun main() { val person = Person("Alice", 30) val result = with(person) { age += 1 "${name} is now $age years old" } println(result) }
with allows you to access the object's members directly and the last expression is returned.The with function takes person as its receiver. Inside the block, age is incremented by 1, so it becomes 31. The last expression is a string that uses the updated age and name. This string is returned and printed.
with and apply functions in Kotlin.with executes the block with the receiver as context and returns the last expression of the block (lambda result). apply executes the block with the receiver as context but returns the receiver object itself.
with on a nullable String. Why does it fail to compile?fun main() { val text: String? = null with(text) { println(length) } }
The variable text is nullable. Calling with(text) without a safe call operator ?. causes a compilation error because with expects a non-null receiver. You must use text?.let { with(it) { ... } } or check for null before calling with.
with calls. What will it print?data class Address(var city: String, var zip: String) data class User(var name: String, var address: Address) fun main() { val user = User("Bob", Address("NYC", "10001")) val result = with(user) { with(address) { "${this@with.name} lives in $city with zip $zip" } } println(result) }
The outer with(user) sets the context to user. Inside, the inner with(address) sets the context to address. The string uses name from the outer scope and city, zip from the inner scope. This prints the full sentence correctly.
with function.with.with is a regular function (not an extension) that takes the receiver object as an argument and executes the block with that receiver as context. It returns the last expression of the block, not the receiver object. It does not require the receiver to be nullable and does not create new objects.