Scope

Every function and block ({ ... }) introduces a new scope for declarations. Each function and block can refer to declarations in its scope or any of the outer scopes.

let x = 10

fun f(): Int {
    let y = 10
    return x + y
}

f()  // is `20`

// Invalid: the identifier `y` is not in scope.
//
y
fun doubleAndAddOne(_ n: Int): Int {
    fun double(_ x: Int) {
        return x * 2
    }
    return double(n) + 1
}

// Invalid: the identifier `double` is not in scope.
//
double(1)

Each scope can introduce new declarations, i.e., the outer declaration is shadowed.

Scope is lexical, not dynamic.

Declarations are not moved to the top of the enclosing function (hoisted).

Last updated

Was this helpful?