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.
_12let x = 10_12_12fun f(): Int {_12 let y = 10_12 return x + y_12}_12_12f() // is `20`_12_12// Invalid: the identifier `y` is not in scope._12//_12y
_10fun 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//_10double(1)
Each scope can introduce new declarations, i.e., the outer declaration is shadowed.
_10let x = 2_10_10fun test(): Int {_10 let x = 3_10 return x_10}_10_10test() // is `3`
Scope is lexical, not dynamic.
_12let x = 10_12_12fun f(): Int {_12 return x_12}_12_12fun g(): Int {_12 let x = 20_12 return f()_12}_12_12g() // is `10`, not `20`
Declarations are not moved to the top of the enclosing function (hoisted).
_10let x = 2_10_10fun f(): Int {_10 if x == 0 {_10 let x = 3_10 return x_10 }_10 return x_10}_10f() // is `2`