In Java one can use curly braces to delineate a block of code with its own scope:
void f() {
{
int x = 1
// do something with x
}
// x not visible here anymore
}
How is this done in Kotlin?
Kotlin apply is an extension function on a type. It runs on the object reference (also known as receiver) into the expression and returns the object reference on completion.
Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped. In order to access the variables of that specific block, we need to create an object for it.
let is often used for executing a code block only with non-null values. To perform actions on a non-null object, use the safe call operator ?. on it and call let with the actions in its lambda. Another case for using let is introducing local variables with a limited scope for improving code readability.
Most objects and functions have names, and each of these names is inside a scope. So the "scope of a function" could mean two things: either the scope defined by the function's body, in which its local variables are declared; or the scope (either a class or a namespace) in which the function name is declared.
You can use run
for this purpose:
inline fun <R> run(block: () -> R): R
(source)
Calls the specified function block and returns its result.kotlin.run
fun f() {
run {
val x = 1
// do something with x
}
// x not visible here anymore
}
This is an inline function (like many other language construct-like functions in Kotlin), so performance-wise it's equivalent to the Java code.
{}
doesn't work since it creates a lambda (which is never actually invoked, so it does nothing). You could call it immediately ({ foo }()
) with the overhead of creating a lambda, or create an inline function that does this for you - which is exactly what run
does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With