Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: how to limit scope within a block?

Tags:

kotlin

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?

like image 664
Ray Zhang Avatar asked Jul 17 '18 20:07

Ray Zhang


People also ask

What is .also 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.

What is block scoped?

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.

How do you use the Let function in Kotlin?

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.

Is scope and function same meaning?

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.


1 Answers

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.

like image 130
Salem Avatar answered Dec 17 '22 09:12

Salem