let scope function?val name: String? = "Alice" val result = name?.let { "Hello, $it!" } ?: "No name" println(result)
name is not null and how let works.The let function executes the block only if name is not null. Here, name is "Alice", so the block returns "Hello, Alice!". The Elvis operator ?: is not used.
class Person { var name: String = "" var age: Int = 0 } val person = Person().apply { name = "Bob" age = 30 } println("${person.name} is ${person.age} years old")
apply returns the object itself after running the block.The apply function runs the block on the object and returns the object itself. Here, it sets name and age before returning the Person instance.
val result = run { val x = 10 val y = 0 x / y } println(result)
The code divides 10 by 0 inside run. This causes an ArithmeticException for division by zero at runtime.
also scope function reduces boilerplate in Kotlin?also lets you do something extra with the object while keeping it unchanged.also lets you run code using the object as it and returns the original object unchanged. This avoids creating extra variables or repeating the object reference.
data class Config(var host: String = "", var port: Int = 0) val config = Config().apply { host = "localhost" }.also { it.port = 8080 } println("Host: ${config.host}, Port: ${config.port}")
apply and also both return the original object after running their blocks.The apply block sets host to "localhost" and returns the object. Then also sets port to 8080 on the same object. The final print shows both updated values.
