Junior
What is the 'run' block in Kotlin and how is it used?
sobes.tech AI
Answer from AI
The run block in Kotlin is a standard library scope function in Kotlin. It is used for:
- Executing a block of code on an object: Called on an object and executes a lambda expression provided as an argument. Inside the lambda, the object is accessible as
this. - Returning a result: Returns the result of the last expression in the lambda.
- Nullable objects: Convenient for working with nullable objects, as when using the safe call operator
?., therunblock will only execute if the object is not null.
Main features:
- Receiver (
this): The object on whichrunis called is accessible inside the lambda asthis. - Return value: The result of the last expression in the lambda.
Examples of usage:
// Example 1: executing code on an object and returning a result
val length: Int = "some string".run {
// 'this' here refers to "some string"
println("String length: ${this.length}")
length // Returns the length of the string
}
// Example 2: working with a nullable object
val nullableString: String? = "another string"
val upperCaseString: String? = nullableString?.run {
// Block executes only if nullableString is not null
toUpperCase() // Returns the string in uppercase
}
val anotherNullableString: String? = null
val anotherUpperCaseString: String? = anotherNullableString?.run {
// Block will not execute, run?. returns null
toUpperCase()
}
// Example 3: creating and configuring an object
val person = run {
val name = "Alice"
val age = 30
Person(name, age) // Assuming a Person class
}