Skip to main content
Version: Current

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.


_12
let x = 10
_12
_12
fun f(): Int {
_12
let y = 10
_12
return x + y
_12
}
_12
_12
f() // is `20`
_12
_12
// Invalid: the identifier `y` is not in scope.
_12
//
_12
y


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

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


_10
let x = 2
_10
_10
fun test(): Int {
_10
let x = 3
_10
return x
_10
}
_10
_10
test() // is `3`

Scope is lexical, not dynamic.


_12
let x = 10
_12
_12
fun f(): Int {
_12
return x
_12
}
_12
_12
fun g(): Int {
_12
let x = 20
_12
return f()
_12
}
_12
_12
g() // is `10`, not `20`

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


_10
let x = 2
_10
_10
fun f(): Int {
_10
if x == 0 {
_10
let x = 3
_10
return x
_10
}
_10
return x
_10
}
_10
f() // is `2`